Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all elements with same id

Tags:

jquery

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/

like image 449
mpapec Avatar asked Feb 11 '14 18:02

mpapec


People also ask

How do I select all elements with the same ID?

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.

Can I have multiple elements with same 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.

What happens when multiple elements have same ID in HTML?

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.

How do I get all elements ID?

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.


2 Answers

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

like image 61
Sachin Avatar answered Sep 28 '22 05:09

Sachin


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')
like image 37
candu Avatar answered Sep 28 '22 06:09

candu