Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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 point).

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">
like image 442
Boris Avatar asked Nov 28 '10 21:11

Boris


People also ask

Can we add ID using jQuery?

We can add an id to an HTML element using jQuery very easily by combining the attr() method with a click event.

Can you add an ID to an A tag in HTML?

Note: In HTML5, id attributes can be used by any HTML tag but in HTML 4.01 there are some restriction to use id attributes. It can not be used by <base>, <head>, <html>, <meta>, <param>, <script>, <style>, and <title> tag.

Can you add id and class in HTML?

Yes, any HTML element (like div, input, nav, body, etc) can have both “id” and “class” together and at the same time. The only difference here is that “id” can have only one unique value and “class” can have more than one.


2 Answers

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.

like image 74
prodigitalson Avatar answered Oct 07 '22 01:10

prodigitalson


Try this

$('div.special').attr('id','your-id');
like image 41
rajangupta Avatar answered Oct 07 '22 03:10

rajangupta