Add another style to tag list using jquery / javascript

Is there a way to add another style class to all li in the ul tag using jquery / javascript / php. Consider the following list.

<ul><li>a</li><li>b</li><li>c</li><li>d</li><li>e</li></ul>

I would like to add the following

<ul><li class='cat1'>a</li><li class='cat2'>b</li><li class='cat3'>c</li><li class='cat4'>d</li><li class='cat5'>e</li></ul>
+3
source share
3 answers

Easier than:

$('ul').children('li').addClass(function (i) {
    return 'cat' + (i+1);
});

http://api.jquery.com/addClass/

+5
source

If you want to set a class, a cheaper way to do this is .attr()with an index in its setter function, like this:

$("ul li").attr("class", function(i) {
  return "cat" + (i+1);
});

If you do not install it and just add , use .addClass(function(i)instead .attr("class", function(i).

+3
source
$('ul').children('li').each(function(i,v){
   $(this).addClass('cat'+(i+1));
});
+1

Source: https://habr.com/ru/post/1764135/


All Articles