target specific HTML element from an object that is mapped

So I have replicated my issue on a smaller level so its easier to work with. The goal is to have an onclick function that shows the content inside the column which is hidden as default, this will ideally be handled through setting display: none and changing to display: flex. I have to use an object hence lodash. I cant use document.getElement because all mapped components share a common classname. The data comes from a database so the amount of columns is unknown and always changing per user requirements.

I guess im looking for a method to target to the classname of the div/tag of the iteration of the map where the onclick for that container is. Any help is appreciated!

import _ from "lodash"
import React from 'react'

const dummyData = {
    columnOne: "item one",
    columnTwo: "item two",
    columnThree: "item three"
}

function TestPage() {
    return (
        _.map(dummyData, (data, key) => {
            return (
                <>
                    <div className="column-container">
                        <p className="heading">{key}</p>
                        <div className="show-content-btn">V</div> //button to toggle content visibility
                    </div>
                    <p className="content">{data}</p> //content to be hidden/shown
                </>
            )
        }

        )
    )
}


export default TestPage

How to not get the same data from my webcrawler

I’m crawling a website that needs the user to click on the link and the result will be displayed on the same page. My crawler is set to click on the link and crawl the data and repeat the process for 30 links. I only get the correct data for the first 4 links but the rest will be the same data from the 4th link or it will take the same data for 4-5 times and then get the next data. How do I make sure that my crawler does not take the same data or make sure that the page loads with the information first then crawls?

This is the image of the website:
enter image description here

This is my code:

for (var j = 1; j < 2; j++) {

    const page = await browser.newPage();
    page.setDefaultNavigationTimeout(0);

    await page.goto('https://startupjobs.asia/job/search?q=&job-list-dpl-page=' + j, {
        waitUntil: "networkidle2",
        timeout: 3000000
    });

    console.log('browsing page ' + j);

    for (var i = 1; i < 31; i++) {

        await page.waitForXPath("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a")
        var b = await page.$x("/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a")
        await b[0].click();

        const elementsToFind = [
            { xpath: "/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/h5/a", propName: 'job_name' },
            { xpath: '//*[@id="suj-single-jobdetail-wrapper"]/div[1]/div[2]/div/h6[2]/a', propName: 'country' },
            { xpath: "/html/body/div[1]/div[3]/div[1]/div/div[1]/ul/li[" + i + "]/div/div[1]/div/p[1]/a", propName: 'company' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[3]/p', propName: 'job_type' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[1]/p', propName: 'salary' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[4]/p', propName: 'skills' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[1]/div', propName: 'job_description' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[3]/div', propName: 'job_requirement' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[2]/div[2]/div', propName: 'job_responsibility' },
            { xpath: '/html/body/div[1]/div[3]/div[2]/div[2]/div[1]/div[2]/div[1]/div[2]/p', propName: 'industry' },
        ];

        var results = {};

        for (var { xpath, propName } of elementsToFind) {
            await page.waitForXPath(xpath);
            var [el] = await page.$x(xpath);
            results[propName] = !el ? 'Not Found' : await (await el.getProperty('textContent')).jsonValue();
            results[propName] = results[propName].replace(/s+/g, ' ')
            results[propName] = results[propName].replaceAll('|', ',')
            results[propName] = results[propName].replaceAll('JOB DESCRIPTION ', '')
            results[propName] = results[propName].replaceAll('JOB REQUIREMENT ', '')
            results[propName] = results[propName].replaceAll('JOB RESPONSIBILITY ', '')
        }

        name.push(results['job_name']);
        country.push(results['country']);
        company.push(results['company']);
        type.push(results['job_type']);
        salary.push(results['salary']);
        skills.push(results['skills']);
        desc.push(results['job_description']);
        req.push(results['job_requirement']);
        resp.push(results['job_responsibility']);
        industry.push(results['industry']);

Child emit does not update v-model prop Array of parent

I’m using this parent component:

<template>
  <div id="cms-custom-editor" class="cms-custom-editor">
    <cms-editor-toolbar v-model:toggles="state.toggles"/>
    <div class="content">Toggle Buttons: {{ state.toggles }}</div>
  </div>
</template>


<script setup>
import CmsEditorToolbar from './cms-editor-toolbar.vue'
import {reactive, ref} from "vue";

const state = reactive({
    toggles: [],
})
</script>

to pass down state.toggles as a prop to the cms-editor-toolbar child component:

<template>
  <div id="cms-editor-toolbar" class="cms-editor-toolbar">
    <button @click="toggleButton"></button>
  </div>
</template>


<script setup>

const props = defineProps({
    toggles: Array,
})

const emit = defineEmits(['update:toggles'])

const toggleButton = () => {
    // ... logic to determine toggleAction
    console.log(toggleAction) // logs correct toggleAction
    emit('update:toggles', toggleAction) //emits only first toggleAction and no other
}

</script>

For whatever reason emit('update:toggles', toggleAction) only emits the first toggleAction to the parent. For every other change, the state.toggles array is not updated.

From the answer in this question, I’ve tried using ref instead of reactive:

<template>
  <div id="cms-custom-editor" class="cms-custom-editor">
    <cms-editor-toolbar v-model:toggles="toggles"/>
    <div class="content">Toggle Buttons: {{ toggles }}</div>
  </div>
</template>


<script setup>
import CmsEditorToolbar from './cms-editor-toolbar.vue'
import {reactive, ref} from "vue";

const toggles = ref([1,2,3])
</script>

but it changes nothing. Again the array is only updated once and no consecutive action has any effect. How do I make this work?

I have an express app deployed on Heroku but I have 404 (not found) error

everything works in my localhost:3000 and using a baseUrl of localhost:5000

I changed my baseUrl to the deployed site(https://mongodb-newsapi.herokuapp.com) but I got an error saying that my site is not found.

Failed to load resource: the server responded with a status of 404 (Not Found)
POST https://mongodb-newsapi.herokuapp.com/api/login 404 (Not Found)

this it my fetchDataApi:

import { axiosInstance } from ‘./axios’;

export const getDataApi = async (url, token) =>{

const res = await axiosInstance.get(`/api/${url}`,{
    headers : {Authorization : token}
})
return res;

}

export const postDataApi =async (url, post, token) => {

const res = await axiosInstance.post(`/api/${url}`, post ,{
    headers: {Authorization: token}

})

return res;

}

export const putDataApi = async (url , post, token) => {

const res = await axiosInstance.put(`/api/${url}`,post,{
    headers :{Authorization: token}
})
return res;

}
export const patchDataApi = async (url , post, token) => {

const res = await axiosInstance.patch(`/api/${url}`, post , {
    headers :{Authorization: token}
})
return res;

}
export const deleteDataApi = async (url , token) => {

const res = await axiosInstance.delete(`/api/${url}`,{
    headers :{Authorization: token}
})
return res;

}

This is my baseUrl:

import axios from ‘axios’;

export const axiosInstance = axios.create({

baseUrl: "https://mongodb-newsapi.herokuapp.com/api"

});

This is my server.js:

require('dotenv').config();

const path = require('path');

const express = require("express");

const mongoose = require('mongoose');

const cookieparser = require('cookie-parser');

const authRouter = require('./routers/authRouter');

const userRouter = require('./routers/userRouter');

const app = express();

app.use(express.json())

app.use(cookieparser());

app.use('/api', authRouter);

app.use('/api', userRouter);

app.use(express.static(path.join(__dirname, "/client/build")));

app.get('*', (req, res) => {
    res.sendFile(path.join(__dirname, '/client/build', 'index.html'));
});

I didn’t add the mongoose.connect because I have my account.

and this is the authCtrl:

const Users = require(“../models/userModel”);

const bcrypt = require(‘bcrypt’);

const jwt = require(‘jsonwebtoken’);

const authCtrl = {

register: async (req, res) => {
    try {

        const { fullName, userName, email, password } = req.body;

        const newUsername = userName.toLowerCase().replace(/ /g, '');

        const user_name = await Users.findOne({ userName: newUsername })

        if(user_name) return res.status(400).json({ msg: 'This UserName Already Exist.' })

        const Email = await Users.findOne({ email: email })

        if(Email) return res.status(400).json({ msg: 'This Email Already Exist.' })

        if(password.length < 8) return res.status(400).json({ msg: 'Password must be atleast 8 Characters.' })

        const passwordHash = await bcrypt.hash(password, 15);

        const newUser = new Users({

            fullName, userName:newUsername, email, password:passwordHash
        })

        const access_token = createAccessToken({id: newUser._id});

        const refresh_token = createRefreshToken({id: newUser._id});

        console.log({access_token, refresh_token})

        res.cookie('refreshtoken', refresh_token, {
            httpOnly: true,
            path: "/api/refresh_token",
            maxAge: 24*30*60*60*1000
        })

        await newUser.save(); 
        
        res.json({
            msg: "Registered Success",
            access_token,
            user: {
                ...newUser._doc,
                password: ''
            }
        })

    } catch (error) {
        res.status(500).json({ msg: error.message })
    }
},
login: async (req, res) => {
    try {
    const {email , password} = req.body;

    const user = await Users.findOne({email})
    .populate("friends following" , "-password")

    if(!user) return res.status(400).json({msg: 'User does not exists'})

    const isMatch = await bcrypt.compare(password,user.password);
    if(!isMatch) return res.status(400).json({msg: 'User Password is incorrect'})

    const access_token= createAccessToken({id: user._id});
    const refresh_token= createRefreshToken({id: user._id});
    

    res.cookie('refreshtoken', refresh_token,{
        httpOnly: true,
        path:'/api/refresh_token',
        maxAge: 24*30*60*60*1000  
    })

    

    res.json({
        msg:"login sucess",
        access_token,
        user:{
        ...user._doc,
        password:''
        }
    })

} catch (err) {
    return res.status(500).json({msg: err.message})
}},logout: async ( req, res ) => {

    try {
        res.clearCookie('refreshtoken', {path: '/api/refresh_token'})

        res.json({msg: "Logged out"})

    } catch (error) {

    return res.status(500).json({ msg: error.message })
    }},generateAccessToken: async (req, res) => {

try {
    const rf_token = req.cookies.refreshtoken;
        
       
    if(!rf_token) return res.status(400).json({msg:"please login now"})

    jwt.verify(rf_token, process.env.REFRESHTOKENSECRET, async(err,result)=>{
        if(err) return res.status(400).json({msg:"Please login now"})

        const user = await Users.findById(result.id).select("-password")
        .populate("friends following")

        if(!user) return res.status(400).json({msg:"user does not exist"})

        const access_token= createAccessToken({id: result.id});

        res.json({
            access_token,
            user
        })
        
    })
} catch (error) {
    res.stauts(500).json({msg: error.message})
}},}const createAccessToken = ( payload) =>{

return jwt.sign(payload, process.env.ACCESSTOKENSECRET, {expiresIn: "1d"})}const createRefreshToken = ( payload) =>{

return jwt.sign(payload, process.env.REFRESHTOKENSECRET,{expiresIn: "30d"})}module.exports = authCtrl

this the github repository:

https://github.com/Noobieprogrammer69/mongodb-heroku

Problem trying to save my google sheet as a pdf to my drive folder

  1. The script works properly as it should when i use it from my gmail acc
  2. but when I share it to another gmail ACC the script keeps getting errors!
  3. The error Exception: Access denied: DriveApp.

I use this code to save a specific sheet to my drive as a pdf and mail it to a specific person.
I want the code to run normally when other users are granted permission to use this sheet. Please help me solve this problem.

function sendReport(range) {
  SpreadsheetApp.getActive().getSheetByName("Customers").hideSheet();
    SpreadsheetApp.getActive().getSheetByName("Products").hideSheet();
      SpreadsheetApp.getActive().getSheetByName("SO Log").hideSheet();
        SpreadsheetApp.getActive().getSheetByName("SOF").hideSheet();

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var SOSheet = ss.getSheetByName("Sales Order");
  var name = SOSheet.getRange('F10').getValue();
  

  var message = {
    to: "[email protected]",
    subject: "Sales Order",
    body: "Hi team,nnPlease find the Sales Order attached.nnThank you",
    name: "Dave",
    attachments: [SpreadsheetApp.getActiveSpreadsheet().getAs(MimeType.PDF).setName("SO"+name)]
  }
  MailApp.sendEmail(message);

  SpreadsheetApp.getActive().getSheetByName("Customers").showSheet();
  SpreadsheetApp.getActive().getSheetByName("Products").showSheet();
  SpreadsheetApp.getActive().getSheetByName("SO Log").showSheet();
  SpreadsheetApp.getActive().getSheetByName("SOF").showSheet();
  

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var token = ScriptApp.getOAuthToken();
  var sheet = ss.getSheetByName("Sales Order");
  var bogus = DriveApp.getRootFolder();


  //Creating an exportable URL
  var url = "https://docs.google.com/spreadsheets/d/SS_ID/exSOrt?".replace("SS_ID", ss.getId());
  var folderID = "1KU7ylGsci9qsVzxU2ZlCW"; // Folder id to save in a folder.
  var folder = DriveApp.getFolderById(folderID);
  var SOcode = ss.getRange("'Sales Order'!F10").getValue()
  var pdfName = "SO" + SOcode;
  

  /* Specify PDF exSOrt parameters
  From: https://code.google.com/p/google-apps-script-issues/issues/detail?id=3579
  */
  var url_ext = 'exportFormat=pdf&format=pdf'        // exSOrt as pdf / csv / xls / xlsx
  + '&size=A4'                       // paper size legal / letter / A4
  + '&SOrtrait=true'                    // orientation, false for landscape
  + '&fitw=true&source=labnol'           // fit to page width, false for actual size
  + '&sheetnames=false&printtitle=false' // hide optional headers and footers
  + '&pagenumbers=false&gridlines=false' // hide page numbers and gridlines
  + '&fzr=false'                         // do not repeat row headers (frozen rows) on each page
  + '&gid=';                             // the sheet's Id
    
  // Convert individual worksheet to PDF

  var response = UrlFetchApp.fetch(url + url_ext + sheet.getSheetId(), {
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()},muteHttpExceptions:true});
    
    
  
  ;
  

var blobs = response.getBlob().setName(pdfName + '.pdf');


var folders = folder.getFoldersByName(pdfName);
folder = folders.hasNext() ? folders.next() : folder.createFolder(pdfName);


var newFile = folder.createFile(blobs);
var newFileLink = newFile.getUrl();
var SOcode = ss.getRange("'SOF'!F12").getValue();
var writePDFLink =  ss.getRange("'SOF'!L1").setValue(newFileLink);

  
  // Define the scope
  Logger.log("Storage Space used: " + DriveApp.getStorageUsed());

}

Download html window object with JS

i have this iframe here, and i want to doanload the window page with pdf inside, js function print() only shows the page, i want to download it automatically, bellow is the full code (i tryed with jspdf too).

<iframe id="conteudoIframe" src="https://eproc.trf4.jus.br/eproc2trf4/controlador.php?acao=acessar_documento_publico&doc=41625504719486351366932807019&evento=20084&key=d924aa9c88bb69126d45bd28a1cf8105cf2d67a50ac78a452b2c71d81ed265b3&hash=6fc65cd1da3fa7dec0b65c442b316d16"  name="superior" width="100%" height="560px"></iframe>

<script>

    downloadPdfFromIframe();

    function downloadPdfFromIframe() {
        var script = document.createElement('script');
        script.src = 'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js';
        document.head.appendChild(script);
        script.onload = () => { setTimeout(download(), 20000); };

        function download() {

            var myIframe = document.getElementById("conteudoIframe").contentWindow;

            myIframe.focus();
            myIframe.print();
            myIframe.close();

            var pdf = new jsPDF();

            pdf.fromHTML(myIframe);
            pdf.save('test.pdf');

            return false;
        }
    }

</script>

How to generate SVG dataURL with p5.js and p5.js-svg?

I am trying to generate an image using p5.js and p5.js-svg and then save the SVG xml as a dataURL for storage. Here is an example script that I’ve simplified for this question:

const canvasWidth = 600;
const canvasHeight = 600;
const bgColor = "#fffcf3";

let unencodedDataURL = "";

const sketch = (p) => {
  p.setup = () => {
    p.createCanvas(canvasWidth, canvasHeight, p.SVG);
    p.background(bgColor);
    p.noLoop();
  }

  p.draw = () => {
    p.noFill();

    p.ellipse(z
      canvasWidth / 2,
      canvasHeight / 2,
      150,
      150
    );
    unencodedDataURL = p.getDataURL();
    console.log(`inside: ${unencodedDataURL}`);
  }
}

const test = new p5(sketch, document.body);
console.log(`outside: ${unencodedDataURL}`);

The first log statement prints the right dataURL. But of course the second log statement executes before the one inside draw() and I cannot figure out how to capture the dataURL correctly. I’m sure I am missing something in the p5.js or p5.js-svg libraries and there is an easier way. But I am stuck. Anyone have an idea here? Thanks in advance!

Getting “Must use import to load ES Module” even though I am using ‘import’

My issue

I’ve been developing a npm package in typescript and I can install it (using npm install) and then use it just fine on regular javascript projects. However, when I install the package and import it from a typescript file, I get the following error:

C:Usersme.devmy_project>ts-node-dev ./test.ts
[INFO] 22:43:02 ts-node-dev ver. 2.0.0 (using ts-node ver. 10.8.0, typescript ver. 4.7.2)
Compilation error in C:Usersme.devmy_projecttest.ts
Error: Must use import to load ES Module: C:Usersme.devmy_projectsrclib.ts
    at Object.<anonymous> (C:Usersme.devmy_projectsrclib.ts:1:7)
    at Module._compile (node:internal/modules/cjs/loader:1105:14)
    at Module._compile (C:Usersmescooppersistnvmnodejsv18.2.0node_modulests-node-devnode_modulessource-map-supportsource-map-support.js:568:25)
    at Module.m._compile (C:UsersmeAppDataLocalTempts-node-dev-hook-42303076870014156.js:69:33)
    at Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at require.extensions..jsx.require.extensions..js (C:UsersmeAppDataLocalTempts-node-dev-hook-42303076870014156.js:114:20)
    at require.extensions.<computed> (C:UsersmeAppDataLocalTempts-node-dev-hook-42303076870014156.js:71:20)
    at Object.nodeDevHook [as .ts] (C:Usersmescooppersistnvmnodejsv18.2.0node_modulests-node-devlibhook.js:63:13)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:827:12)
[ERROR] 22:43:02 Error: Must use import to load ES Module: C:Usersme.devmy_projecttest.ts

Project structure

My project structure is a little bit like this:

my_project/
└──dist/
│ └──lib.js        (my main file, transpiled)
│
└──src/
│ └──lib.ts        (my main file)
│
└──index.d.ts
└──index.js          (heart of the package, exports lib.js contents)
│
└──test.ts           (targeted test file)
│
└──package.json
└──tsconfig.json

Files

And the files are like this:

// src/lib.ts

export default class MyClass {
  // ...
}
// ./index.js

import MyClass from './dist/lib.js';

export default MyClass;
// ./test.ts

// This file is meant to be a "simulation" of another project importing the package's contents.

// My confusion raises here. The error tells me to use 'import' to load the module.
// But I am already using it? Unless this is not what the compiler meant (most likely the issue)
import MyClass from "my_project";

const my_class = new MyClass();
// ./package.json

{
  "name": "my_project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {},
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "my_dependency": "github:author/my_dependency"
  },
  "dependencies": {
    "typescript": "^4.7.2"
  }
}
// ./tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "ES6",
    "strictNullChecks": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  },
  "includes": ["./src/**/*"]
}

Disclaimer

I didn’t want to straight copy and paste my code into the internet, so I removed and refactored a lot of it, but I’ve made sure to make it as faithful to the real code. Feel free to ask me for more details or info if necessary.

I am gettng an error on my addeventlistener but can’t spot the issue [duplicate]

I am creating a multiple choice quiz using javascript. I have the below as my event listener

    start.addEventListener("click",startQuiz);

 function startQuiz(){
    start.style.display = "none";
    renderQuestion();
    quiz.style.display = "block";
    renderProgress();
    renderCounter();
    TIMER = setInterval(renderCounter,1000);

and this is a snipet of the HTML

  <div id="container">
        <div id="start">Start Quiz!</div>
        <div id="quiz" style="display: none">
            <div id="question"></div>
            <div id="qImg"></div>
            <div id="choices">
                <div class="choice" id="A" onclick="checkAnswer('A')"></div>
                <div class="choice" id="B" onclick="checkAnswer('B')"></div>
                <div class="choice" id="C" onclick="checkAnswer('C')"></div>
            </div>

I am getting the below error in google devs:

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)

Any suggestions would be helpful as I am just learning javascript!

Add events to a NodeList

https://www.smashingmagazine.com/2014/01/understanding-javascript-function-prototype-bind/#tidier-event-binding-with-queryselectorall demonstrates an approach of adding events to a NodeList:

var unboundForEach = Array.prototype.forEach,
    forEach = Function.prototype.call.bind(unboundForEach);

forEach(document.querySelectorAll('.klasses'), function (el) {
    el.addEventListener('click', someFunction);
});

I don’t quite understand two things:

  1. Why does it need to bind the unboundForEach?
  2. Why does it use Function.prototype.call.bind instead of Function.prototype.bind?

What’s the conventional way to parse a markdown-like language into an abstract syntax tree?

I’m writing a parser for a niche markup language like Markdown. To make things easier to understand, I’ll just use Markdown as an example.

I’ve done some research and learned that the conventional way to parse a markdown document into an AST consists of the following steps:

  1. Parse the document into an array of tokens.
  2. Transform the tokens into an AST.

I’m having a problem with the first step. Most tutorials online use regex to do it. here is an example written in javascript:

function getTokensByRule(text, rule) {
    const tokens = [];
    let match = rule.exec(text);
    do {
        tokens.push(match);
    } while((match = rule.exec(text)) !== null);
    return tokens;
}

function getTokens(text) {

    // overly simplified rules, there may be a lot more in reality
    const rules = {
        italic: /*[^*]**/g,
        code: /`[^`]*`/g,
    };

    const tokens = [];
    for (const ruleName in rules) {
        const rule = rules[ruleName];
        tokens.push(...getTokensByRule(text, rule))
    }
    return tokens;
}

const tokens = getTokens("some `markdown` *texts*");
console.log(tokens);

// output:
// [
//     [
//         '*texts*',
//         index: 16,
//         input: 'some `markdown` *texts*',
//         groups: undefined
//     ],
//     [
//         '`markdown`',
//         index: 5,
//         input: 'some `markdown` *texts*',
//         groups: undefined
//     ]
// ]

It works, but I see a problem in it: this would probably be slow. It parses the document against each regex rule. The time complexity would be close to O(n * r), where n is the length of the document and r is the number of regex rules.

So my question is, is this the conventional way to parse the markdown language? Is there any faster or better way to achieve it?

javascript element.remove() not remove dom

element.remove() seem to weird.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    class View {
      constructor() {
        this.parent = document.querySelector('#root')
      }
      template() {
        return `
        <div>Random Num</div>
        <div>${Math.random()}</div>
        <button type='button'>Reset Random Num</button>
      `
      }
      render() {
        const templateElement = document.createElement('template')
        templateElement.innerHTML = this.template()
        templateElement.content
          .querySelector('button')
          .addEventListener('click', () => {
            this.rerender()
          })
        this.parent.append(templateElement.content)
      }
      rerender() {
        this.parent.childNodes.forEach((item) => {
          // here is the problem
          item.remove()
        })
        // const templateElement = document.createElement('template')
        // templateElement.innerHTML = this.template()
        // this.parent.append(templateElement.content)
      }
    }
    const viewIns = new View()
    viewIns.render()
  </script>
</html>

when I click the button, doms don’t get removed at all,and then I clicked the button again ,only the div contains the random number left,I’m really confused why is that.