0

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

1
  • why you have jquery tag?? Commented Nov 19, 2013 at 13:22

4 Answers 4

1

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); 
});
Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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..

2 Comments

my list items will be dynamically uploaded by getting values from database. i wont be knowing the number of items. in that case it is not feasible to refer li items by giving id.
You are already successfully retrieving the array you are after, the only problem is you are trying to access the ID field which has not been set. The array lisX[] can be manipulated to do as you wish. Ofc, when you print the items from the database, you could use that opportunity to assign IDs to the list items if they are needed.
0

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 ;-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.