91

Is there any method available to add IDs like there is for adding a class - addClass()?

PJ Brunet
  • 3,615
  • 40
  • 37
eozzy
  • 66,048
  • 104
  • 272
  • 428
  • addClass() is not a selector. A selector is somethings defines as element(s) before doing something with/to it. addClass() is a method, something that has an action upon something. – Phish Aug 20 '14 at 11:56
  • 1
    can you replace word 'selector' for 'functionnality' in your question? – Milche Patern Dec 08 '15 at 14:14
  • Possible duplicate of [Adding attribute in jQuery](https://stackoverflow.com/questions/5995628/adding-attribute-in-jquery) – Makyen Oct 05 '18 at 21:43

4 Answers4

192

ID is an attribute, you can set it with the attr function:

$(element).attr('id', 'newID');

I'm not sure what you mean about adding IDs since an element can only have one identifier and this identifier must be unique.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
  • 1
    I'm not sure how this answers the question. This does not add an id, it sets one, which can be a big difference if you are using dynamic IDs – Ian Steffy Oct 07 '14 at 14:08
  • My interpretation of the question: looking at a `
    ` there's no ID, and if for whatever reason you can't add the id by hand, you might want to automate adding an ID with Javascript/jQuery.
    – PJ Brunet Nov 05 '19 at 18:55
13

do you mean a method?

$('div.foo').attr('id', 'foo123');

Just be careful that you don't set multiple elements to the same ID.

scunliffe
  • 62,582
  • 25
  • 126
  • 161
9

Like this :

var id = $('div.foo').attr('id');
$('div.foo').attr('id', id + ' id_adding');
  1. get actual ID
  2. put actuel ID and add the new one
Sylvain
  • 91
  • 1
  • 1
  • I'm not sure this is what the OP wanted... but more importantly there can only be 1 `id` attribute value. More specifically the specs for an `id` attribute clearly indicate that it may **not** contain spaces: http://www.w3.org/TR/html401/types.html#type-name – scunliffe Jun 28 '13 at 21:58
3

I've used something like this before which addresses @scunliffes concern. It finds all instances of items with a class of (in this case .button), and assigns an ID and appends its index to the id name:

$(".button").attr('id', function (index) {
 return "button-" + index;
});

So let's say you have 3 items with the class name of .button on a page. The result would be adding a unique ID to all of them (in addition to their class of "button").

In this case, #button-0, #button-1, #button-2, respectively. This can come in very handy. Simply replace ".button" in the first line with whatever class you want to target, and replace "button" in the return statement with whatever you'd like your unique ID to be. Hope this helps!