Reputation: 559
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
Upvotes: 0
Views: 2733
Reputation:
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);
});
Upvotes: 1
Reputation: 1983
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 ;-)
Upvotes: 0
Reputation: 2350
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..
Upvotes: 0
Reputation: 37506
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.
Upvotes: 0