简体   繁体   中英

Dom manipulation with for loop

I am trying to do append() function. i have a table of data. i run a loop to first remove text in cell then i will append a new tag.this usecase is to create a progress bar. for an example

data sample inside cell is eg 39% 39% 82% etc etc

        let cf_percent;
        let cf_regex;
        for(let i = 0 ;i < tbl[0].length;i++){
            cf_percent = tbl[0][i].innerHTML
            cf_regex = cf_percent.replace(/[`~%]/gi, '');
            console.log(cf_regex)
            
            //Clear fields
            tbl[0][i].innerHTML = ''
            tbl[0][i].append('<p>Textfield</p>');
        }

It should return texfield but instead, it is returning '<p> textfield </p>' in table cell.it should return textField. i have tried.html() but this does not work for this usecase.

I will suggest to use:

let cf_percent;
        let cf_regex;
        for(let i = 0 ;i < tbl[0].length;i++){
            cf_percent = tbl[0][i].innerHTML
            cf_regex = cf_percent.replace(/[`~%]/gi, '');
            console.log(cf_regex)
            
            //Clear fields
            tbl[0][i].innerHTML = ''
            tbl[0][i].innerHTML += `<p>Textfield</p>`;
        }

in d3.js append function appends a new element with the specified name as the last child of each element in the current selection, returning a new selection containing the appended elements. So to append p element use: tbl[0][i].append("p") and to set text use .text() further: eg

tbl[0][i].append("p").text("Textfield")

You have 2 options. The first is along what you are trying to do where you set the innerHTML to a string. The second is actually generating an element and then appending it. Your current scenario seems to be mixing the two.

 const div1 = document.getElementById('sample1'), div2 = document.getElementById('sample2'), p = document.createElement('p'); div1.innerHTML = '<p>This set the innerHTML</p>'; p.innerText = 'This is ap appended to a div'; div2.appendChild(p);
 #sample1 { background-color: red; } #sample2 { background-color: yellow; }
 <div id="sample1"></div> <div id="sample2"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM