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

Popular posts from this blog

node.js - Node js - Trying to send POST request, but it is not loading javascript content -

javascript - Replicate keyboard event with html button -

javascript - Web audio api 5.1 surround example not working in firefox -