简体   繁体   中英

how to remove and create new ul li tag in html using javascript

Can anyone help me to get this work in d3js

My html tag are as below

<div id="source1"><ul><li>Source</li></ul></div>

i want to modify the <li>Source</li> with <li>some other text</li> by removing all the UL LI tags in DIV id source1 and creating new UL LI tags in div id source1

My code is here

d3.selectAll("ul").remove()

d3.selectAll("li").remove()

var test=document.getElementbyId('source1');
var ul=document.createElement('ul');
document.body.appendChild(test);
test.appendChild(ul);
var li=document.createElement('li');
ul.appendChild(li);
li.innerHTML="some other text";

here is code that should work :

var test=document.getElementById('source1');
var li=test.children[0].children[0];
li.innerHTML="some other text";

Instead of recreating element you can change text only.

If your moto is to just edit the text in the li tag, you can go for "innerHtml" javascript method. This is the best method Eg.

<div id="source1"><ul><li id="liId">Source</li></ul></div>
 document.getElementById('liId').innerHTML="Some other text";

If you want to replace element(in your case, which is not required) you can use this,

<div id="source1">
<ul><li id="liId">Source</li></ul>
</div>

<script>
var para = document.createElement("li");
var node = document.createTextNode("Some other Text");
para.appendChild(node);

var parent = document.getElementById("source1");
var child = document.getElementById("liId");
parent.replaceChild(para,child);
 </script>

Hope this helps

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