91

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

3
  • 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. Commented Aug 20, 2014 at 11:56
  • 1
    can you replace word 'selector' for 'functionnality' in your question? Commented Dec 8, 2015 at 14:14
  • Possible duplicate of Adding attribute in jQuery Commented Oct 5, 2018 at 21:43

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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
My interpretation of the question: looking at a <div> 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.
14

do you mean a method?

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

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

Comments

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

1 Comment

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: w3.org/TR/html401/types.html#type-name
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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.