开发者

How to add an id attribute to a html tag with a certain class using jQuery?

开发者 https://www.devze.com 2023-01-27 13:26 出处:网络
I have a link with a class of special and I want to add an id attribute to it. Only one element in my document will have this class at any one time (I may remove and add a new one at some poin开发者_

I have a link with a class of special and I want to add an id attribute to it.

Only one element in my document will have this class at any one time (I may remove and add a new one at some poin开发者_如何转开发t).

How would I add an id attribute to the element to change it from this:

<div class="special">

to this:

<div id="special-12345" class="special">


Adding the attribute is easy:

$('.special').attr('id', 'your-id-value');

The more potentially problematic part will be ensuring that the id's you are adding are unique.


Try this

$('div.special').attr('id','your-id');


$(".special").attr("id","special-" + (new Date()).getTime());


Don't have the reputation to add a comment, but i believe it's benefitial enough for others searching for answer to state, that

attr();

Doesn't simply add the attribute but rather sets it. Important when there already is some set ID on the element.


You can add id with:

$('.special').attr('id', 'id-value');

Do you want change id?

$('.special').removeAttr('id').attr('id', 'id-value');
0

精彩评论

暂无评论...
验证码 换一张
取 消