Hello All,
I know this probably simple but I am having trouble figuring it out. How would I get an array of all the <li> elements within a <ul>?
Any help would be great! Thanks.
Hello All,
I know this probably simple but I am having trouble figuring it out. How would I get an array of all the <li> elements within a <ul>?
Any help would be great! Thanks.
HTML Code:<script type="text/javascript"> var ray={ ulCycle:function(ulID) { var liArray=this.listArray(ulID); for(var i=0;i<liArray.length;i++) alert(liArray[i].firstChild.nodeValue); // Show the list in the UL }, listArray:function(ulID) { return document.getElementById(ulID).getElementsByTagName('li'); } } function ulCycle(el) { this.el=document.getElementById(el).getElementsByTagName('li'); for(var i=0;i<this.el.length;i++) { alert(this.el[i].innerHTML); } } window.onload=function(){ ray.ulCycle('ul2'); // Pass the ID of the UL you want to loop through } </script> <ul id="ul1"> <li>List 1</li> <li>List 2</li> <li>List 3</li> <li>List 4</li> <li>List 5</li> </ul> <ul id="ul2"> <li>List A</li> <li>List B</li> <li>List C</li> <li>List D</li> <li>List E</li> </ul> <ul id="ul3"> <li>List A1</li> <li>List B2</li> <li>List C3</li> <li>List D4</li> <li>List E5</li> </ul>
Learn how to code at 02geek
The more you learn, the more you'll realize there's much more to learn
Ray.ph!
Moshambi (11-06-2008)
Use getElementsByTagName() method.
From the above code, you can use getElementsByTagName() in coordination with getElementById():
Hope that makes sense.Code:document.getElementById('ul_ID').getElementsByTagName('tag_name');
Learn how to code at 02geek
The more you learn, the more you'll realize there's much more to learn
Ray.ph!
Cool this wwas exactly what I was trying to do!
Thanks a bunch
Note: The getelementsByTagName() method returns a live nodeList, not an array. So, as you cycle through it, if you are adding elements to it or removing elements from it, its length will change, and depending upon which way you are going as you cycle through it, and whether you are adding or subtracting elements from it, or both, values may get out of range and cause an error. Also, any changes to the individual nodes will immediately be updated to the nodeList. If you need an array you can first:
After that, lis will be an ordinary array.Code:for (var lis = [], nl = document.getElementById('ulid').getElementsByTagName('li'), i = nl.length - 1; i > -1; --i) lis[i] = nl[i];
- John________________________
Show Additional Thanks: International Rescue Committee - Donate or: The Ocean Conservancy - Donate or: PayPal - Donate
Bookmarks