PDA

View Full Version : Getting all the <li> elements



Moshambi
11-06-2008, 08:29 AM
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.

rangana
11-06-2008, 08:53 AM
<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>

rangana
11-06-2008, 09:34 AM
Use getElementsByTagName() (https://developer.mozilla.org/En/DOM/Element.getElementsByTagName) method.

From the above code, you can use getElementsByTagName() in coordination with getElementById():


document.getElementById('ul_ID').getElementsByTagName('tag_name');


Hope that makes sense.

Moshambi
11-06-2008, 07:52 PM
Cool this wwas exactly what I was trying to do!

Thanks a bunch

jscheuer1
11-06-2008, 08:03 PM
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:


for (var lis = [], nl = document.getElementById('ulid').getElementsByTagName('li'), i = nl.length - 1; i > -1; --i)
lis[i] = nl[i];

After that, lis will be an ordinary array.