简体   繁体   中英

How to access the dynamically created <li> Element in javascript?

I am trying to access the dynamically created elements <li> .I have tried it by using TagName but its not working...

HTML

 <body onload="ops()">
 <div id="list"></div>

JavaScript

  function ops()
 {
     var ar=["Nucleotide_chnage","Ethinicity","study of dance","disease"];
     var text="<ul>";
  for(i in ar)
  {

     text+="<li>"+ar[i]+"<span>"+"&gt"+"</span>"+"</li>";

 }
     text+="</ul>";
     var y=document.getElementById("list").innerHTML=text;
}

 var close=document.getElementByTagName("li");
 for(var i=0;i<close.length;i++)
 {
    close[i].addEventListener("click",function(){

     this.parentElement.style.display='none';
 });

 }

I want to clarify that onload events are possible to close by click event?

This should work, explained in comments and improved a little removing concatenation.

var body = document.querySelector("body");
  var ar=["Nucleotide_chnage","Ethinicity","study of dance","disease"];

  var ul = document.createElement('ul');
  for(i in ar) {
    // text+="<li>"+ar[i]+"<span>"+"&gt"+"</span>"+"</li>";
    var li = document.createElement('li');
    var span = document.createElement('span');
    span.textContent = "&gt";

    li.appendChild(span);
    ul.appendChild(li);
  }

  // You have to attach the elements to DOM to create listeners
  body.appendChild(ul);


  // you have a typo
  // getElementByTagName is getElementsByTagName
  var close=document.getElementsByTagName("li");
    for(var i=0;i<close.length;i++) {
        close[i].addEventListener("click",function(){
            this.parentElement.style.display='none';
        });
  }

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