Select all elements with same id

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')

Since ID can be accessed as any attribute $('[id="x1"]') will do the trick.

Demo: http://jsfiddle.net/VkaWN/

But if possible at all influence design change, it's bad mojo.


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

Tags:

Jquery