msm.oliveira
msm.oliveira

Reputation: 211

Is it possible add an id to an element which already has an id

I was adding a class to an element like this:.addClass('middle_item')

Then i notice that class in unique, so i should change it to an id .attr("id", 'middle_item');, right?

So, can I add another id to an element which already has an id?

If the answer is yes, theres any way to get and save the first id in a variable?

Example Fiddle here

Upvotes: 2

Views: 374

Answers (3)

jeanpier_re
jeanpier_re

Reputation: 835

You can only have one id per element see this answer for more details so you have to remove the previous id but that's weird.

All this considered, here is how you could achieve this but I don't imagine that this is actually what you want

$("#listitem1").removeAttr("id").attr("id", "newID")

In the above code I'm chaining the methods by first selecting #listitem1 then removing it's id attribute and finally applying a new id.

Also in your example var i = $("middle_item").attr("id"); returns undefined because the id never applied but if you did you made two errors: first you wrote $("middle_item") when it should have been $("#middle_item") and second because you didn't first remove the previous id.

jQuery Docs

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method.

Upvotes: 2

talemyn
talemyn

Reputation: 7950

No, that is not allowed . . . while there are differences between HTML 4 and HTML 5 in regards to "legal ID values", one of the things that they have in common is that spaces are not allowed in the values:

HTML 4 definition - http://www.w3.org/TR/html4/types.html#type-id

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

HTML 5 definition - http://www.w3.org/TR/html5/dom.html#the-id-attribute

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

As such, without spaces, you can only ever have a single ID value.

Upvotes: 2

Dan Ward
Dan Ward

Reputation: 182

Like @Pointy said, you can only have 1 ID on an element. It seems like you are trying to apply an ID or class to the <li> in order to grab it later? If so, there are better ways of getting at the middle item in a list with jQuery using :nth-child() selector, like in this post. Selector documentation here.

Upvotes: 2

Related Questions