10

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/

mpapec
  • 50,217
  • 8
  • 67
  • 127

7 Answers7

11

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

Sachin
  • 40,216
  • 7
  • 90
  • 102
9

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')
Community
  • 1
  • 1
candu
  • 2,827
  • 23
  • 18
3

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.

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
2

This will work (Yes, it's a long shot).

$("[id]").each(function(){
 if($(this).attr("id")=="x1"){
  // do something
 }
});

ID's must be unique. If you use class instead of ID, it would have been easy to select them all. Also, since you can select multiple elements by attribute, you can use $('[id=x1]')

Subin
  • 3,445
  • 1
  • 34
  • 63
1

You should use a class to identify the wrong id used in this case.

console.log($('body #x1'));
John
  • 544
  • 4
  • 19
0

just add for each loop to specify all the elements having class .one and it will automatically turn the all elements having class .one to .blue color. Cheers! :)

   let clonedEle = $(".one").clone();

    clonedEle.insertAfter(".one");

    $(".one").click(function() {
      $(".one").each(function(){
        $(this).css("background-color", "blue");
       });
    });
charan tej
  • 26
  • 5
0

Always us different id. Simply add custom attribute on your div and the try doing like below:

<div data-id='x1' id='div1'></div>
<div data-id='x1' id='div2'></div>
<div data-id='x2' id='div3'></div>

var number = 6;
var myDiv = $('div[data-id='x1']');