addID in jQuery?

JqueryJquery Selectors

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

do you mean a method?

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

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

Solution 3 - Jquery

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

Solution 4 - Jquery

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestioneozzyView Question on Stackoverflow
Solution 1 - JqueryChristian C. SalvadóView Answer on Stackoverflow
Solution 2 - JqueryscunliffeView Answer on Stackoverflow
Solution 3 - JquerySylvainView Answer on Stackoverflow
Solution 4 - JqueryDanny DicksonView Answer on Stackoverflow