Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Add id to each element based on the count in JQuery

Tags:

jquery

<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/

like image 391
PRANAV Avatar asked Nov 28 '25 23:11

PRANAV


2 Answers

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

like image 171
Raptor Avatar answered Dec 01 '25 12:12

Raptor


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.

like image 38
Tahir Ahmed Avatar answered Dec 01 '25 12:12

Tahir Ahmed



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!