如何使用jQuery将id属性添加到具有某个类的html标记?

时间:2021-08-26 20:31:39

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

我有一个特殊类的链接,我想添加一个id属性。

Only one element in my document will have this class at any one time (I may remove and add a new one at some point).

我的文档中只有一个元素在任何时候都有这个类(我可能会删除并在某个时候添加一个新元素)。

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

如何向元素添加id属性以从中更改它:

<div class="special">

to this:

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

5 个解决方案

#1


24  

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.

更有潜在问题的部分将确保您添加的ID是唯一的。

#2


9  

Try this

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

#3


5  

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

#4


2  

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.

不是简单地添加属性而是设置它。当元素上已经有一些设置ID时很重要。

#5


1  

You can add id with:

你可以添加id:

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

Do you want change id?

你想要改变身份证吗?

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

#1


24  

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.

更有潜在问题的部分将确保您添加的ID是唯一的。

#2


9  

Try this

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

#3


5  

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

#4


2  

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.

不是简单地添加属性而是设置它。当元素上已经有一些设置ID时很重要。

#5


1  

You can add id with:

你可以添加id:

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

Do you want change id?

你想要改变身份证吗?

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