简体   繁体   中英

How to store li values in dynamically generated ul , in an array?

I have a unordered list, which will be generated dynamically . I need to store the items in a list in an array .

this is my list:

 <div id="xaxizd">
 <ul id="xaxiz"   style="list-style: none;" >
 <li></li>
 </ul>
 </div>

I am trying to retrieve the value using this function. (Below mentioned code is in document.ready function is self)

  var lisX = document.getElementById("xaxizd").getElementsByTagName("li"); 
  alert(lisX[0].id);

But it is not working. Is there any other way to store list item values ? please help by finding the mistake or by suggesting any other method .

Thanks in advance

Fiddle

No jQuery:

var arr = document.getElementById("xaxiz").getElementsByTagName("li");
for (i=0;i<arr.length;i++) {
    alert(arr[i].id);
}

jQuery:

$("#xaxiz li").each(function() {
    alert(this.id); 
});

It would be easier for you to do it the other way around. Building up your model (such as this array) from the presentation layer (the list) is backwards from good UI design. If you start over the other way you'll find it easier. Example:

function refreshUL(sources) {
    var ul = jQuery('#myUL');
    jQuery.each(sources, function(i, source) {
         jQuery('<li/>').attr({ key: source.value})
              .text(source.text).appendTo(ul);
    });
}

But as to your immediate issue, your code won't work because you have no id attribute in those <li/> tags.

Your li does not have an ID set, so it is returning an empty string, change your HTML to:

<div id="xaxizd">
<ul id="xaxiz" style="list-style: none;" >
   <li id="test"></li>
</ul>
</div>

and try again..

I just looked it up in the jQuery documentation. You can loop through all li elements:

$( "li" ).each(function( index ) {
console.log( index + ": " + $( this ).attr( "id" );
});

Of course you should also add an "id" tag to the html code ;-)

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