Incrementally add number to all elements with same class name using jQuery -
i couldn't lingo right in order find out how this. on page have numerous span elements class "z-title". add additional class these elements includes incremental number, example
from
<span class="z-title">hello</span> <span class="z-title">hello</span> <span class="z-title">hello</span>
to this
<span class="z-title tab1">hello</span> <span class="z-title tab2">hello</span> <span class="z-title tab3">hello</span>
thanks help!
jquery's .addclass()
function can accept callback function argument, in case callback called once per element in jquery object. callback receives index of current element argument, , string value returned callback should name of class add element.
the element indices start @ zero, of course can add 1 each index class names want:
$(".z-title").addclass(function(i) { return "tab" + (i + 1) })
.tab1 { color: red; } .tab2 { color: blue; } .tab3 { color: green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <span class="z-title">hello</span> <span class="z-title">hello</span> <span class="z-title">hello</span>
Comments
Post a Comment