Is there any method available to add IDs like there is for adding a class - addClass()?
- 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.user2703728– user27037282014-08-20 11:56:51 +00:00Commented Aug 20, 2014 at 11:56
- 1can you replace word 'selector' for 'functionnality' in your question?Milche Patern– Milche Patern2015-12-08 14:14:51 +00:00Commented Dec 8, 2015 at 14:14
- Possible duplicate of Adding attribute in jQueryMakyen– Makyen ♦2018-10-05 21:43:09 +00:00Commented Oct 5, 2018 at 21:43
4 Answers
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.
2 Comments
<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.Like this :
var id = $('div.foo').attr('id'); $('div.foo').attr('id', id + ' id_adding'); - get actual ID
- put actuel ID and add the new one
1 Comment
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-nameI'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!