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">
We can add an id to an HTML element using jQuery very easily by combining the attr() method with a click event.
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.
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.
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');
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