PDA

View Full Version : Resolved Assign a classname to <li> only if it has child



TheJoshMan
01-07-2009, 08:51 AM
I was wondering if this is possible with js?

Say you've got several nested <ul> elements, and you'd like to use a small bit of js to assign the "parent" <li>'s a special classname...



<ul>
<li>Child</li>
<li>Child</li>
<li>Parent
<ul>
<li>Grandchild</li>
<li>Grandchild</li>
</ul>
</li>
<li>Child</li>
</ul>


So how could you go about getting js to autmatically assign the special classname to the "Parent" <li> shown above?

codeexploiter
01-07-2009, 09:29 AM
The following function should be able to do this,


function addClassToLis() {
var uls = document.body.getElementsByTagName('ul');
for (var i = 0; i < uls.length; ++i) {
var lis = uls[i].getElementsByTagName('li');
for (var j = 0; j < lis.length; ++j) {
var chuls = lis[j].getElementsByTagName('ul');
if (chuls.length > 0) {
lis[j].className = "parent";
}
}
}
}

Hope this helps.

TheJoshMan
01-07-2009, 09:42 AM
perfect! Thank you very much!