<div class="tile_nav">
<ul>
<li><span class="ullevel2"><span>Sample text</span></span></li>
<li><span class="ullevel2"><span>Sample text</span></span></li>
<li><span class="ullevel2"><span>Sample text</span></span></li>
<li><span class="ullevel2"><span>Sample text</span></span></li>
</ul>
</div>
I have used
$(".tile_nav .ullevel2 span").attr('id', function(index) {
return "testDiv" + ($(this).index() + 1);
});
How to add id to each element based on the length by jQuery each on page loading? https://jsfiddle.net/4LLocqau/1/
You can use the following function:
var cnt = 1;
$(".tile_nav .ullevel2 span").each(function () {
$(this).attr('id', function (index) {
return "testDiv" + cnt;
});
cnt++;
});
.each() is useful in your case to loop through the elements.
Working Demo: JSFiddle
Try this:
$('.tile_nav .ullevel2 span').each(function(index) {
$(this).attr('id', 'testDiv' + (index + 1));
});
jsFiddle.
You could use an each() loop to iterate through the span objects. And this each() sends an index value that we can further utilise to form and apply an id.
I am assuming of course that you want to add id attribute to the inner-most span element. Correct me if I am wrong.
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With