mercredi 31 décembre 2014

How to add a class for html tag () depending a condition with javascript


I need to add style classes according to the number of <span> in a <li> I start with the following code:



$(document).ready(function() {
var ul = document.getElementsByTagName("ul");
for (var i, li; li = ul.childNodes[i]; i++) {
if (li.tagName == 'LI') {
var container = li.getElementsByTagName("span");
var nb = container.length;
if (nb == 1)
{
container[0].childNodes[0].setAttribute("class", "class1")
}
else if (nb == 2)
{
container[0].childNodes[0].setAttribute("class", "class2")
container[0].childNodes[1].setAttribute("class", "class3")
}
}
}});


JsFiddle Example





Aucun commentaire:

Enregistrer un commentaire