2

If I have just the #index on my body element, the length method gives me the correct answer of 1. But if I have a second ID on this body element the length method gives me 0. Whats wrong with that?

$("#index").length

You can test it here. Just remove the .removeme from the body tag and try the command in the developer console again.

http://fiddle.jshell.net/RmqsS/2/show/

Any ideas or suggestions?

Wesley Murch
  • 101,186
  • 37
  • 194
  • 228
Denny Mueller
  • 3,505
  • 5
  • 36
  • 67
  • 2
    You can't have two IDs, and an ID cannot contain spaces. – Wesley Murch Oct 01 '13 at 13:54
  • Why two IDs? I don't think that is correct. Class can be many but not IDs. – Harry Oct 01 '13 at 13:55
  • Refer to this post: http://stackoverflow.com/questions/192048/can-an-html-element-have-multiple-ids – tymeJV Oct 01 '13 at 13:55
  • You shouldn't have duplicate IDs in the same page. Change that to a class instead – Venkata Krishna Oct 01 '13 at 13:55
  • you're not supposed to have the same id twice. use class instead – Pixou Oct 01 '13 at 13:55
  • A HTML element should only have one ID: http://stackoverflow.com/questions/192048/can-an-html-element-have-multiple-ids – simey.me Oct 01 '13 at 13:56
  • [This attribute assigns a name to an element. This name must be unique in a document.](http://www.w3.org/TR/html401/struct/global.html#h-7.5.2) – jbabey Oct 01 '13 at 13:56
  • In the rare scenario where one doesn't have access to the source HTML e.g when building proxies, in order to target an element that had multiple ids this css selector can be used [id="one two three"']. The string literal of the id attribute. – JisuKim82 Aug 18 '17 at 17:26

3 Answers3

4

DEMO

You cannot have multiple id's for a element.

because the browser will only render the first one

$("#inp").val($("#index").length); //sets value 1
              ^ //add $ here

Read

Can a HTML element have multiple unique ID attributes?

id attribute

Community
  • 1
  • 1
Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107
2

ID 's are meant to be unique identifiers for elements. If you want to have multiple identifiers on an element. use classes.

Documentation:

http://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute

ExceptionLimeCat
  • 6,191
  • 6
  • 44
  • 77
0

An id is unique. A tag should have only one id and a id can't be used multiple times.

Johni
  • 2,933
  • 4
  • 28
  • 47