I know that element id should be unique but which selector should be used when needed
$("*#x1")
, $("[id=x1]")
, or something else?
HTML
<div id="x1">A</div>
<div id="x1">B</div>
<div id="x2">C</div>
http://jsfiddle.net/2VHBC/2/
JQuery selector $("#idofelement") finds the first matching element with the ID but what to do if you need to apply a style to all the elements with the same ID. Here is a solution: You can use JQuery selector $("[id='idofelement']") to select all the elements with matching ID.
The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.
ids contain only first div element. So even if there are multiple elements with the same id, the document object will return only first match.
Accessing Elements by ID You can get an element by ID with the getElementById() method of the document object. In the Console, get the element and assign it to the demoId variable. Logging demoId to the console will return our entire HTML element.
Yes your html markup is invalid and Id must be unique on the page but attribute
selector does your work in that case.
alert($('[id=x1]').length);
Js Fiddle Demo
As several other answers mentioned: do not duplicate IDs. It is a terrible, horrible, no good, very bad idea: Can multiple different HTML elements have the same ID if they're different elements?
I'm not sure what happens if you do this, but I'd wager it's up to the browser, which means you can't depend on it being reasonable.
Use class
instead:
<div class="x1">A</div>
<div class="x1">B</div>
<div class="x2">C</div>
And then use jQuery's class selector, which matches the CSS syntax:
$('.x1')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With