Sooraj
Sooraj

Reputation: 10567

JQuery:Selecting second element in case element with same ID exists

I know it's not a good practice to use same id for different element , but in a case I am forced to use same id for two different elements ( which will be automatically generated in the original program)

I'm trying to select the second element with the same id ( or when scaling say , nth element ).

Is there a way to do this ?

I have created a code snippet here , that shows the problem.

$("#btn").click(function(){
  
  $("#test").css("background","blue");

});
#test {
  height: 100px;
  width: 100px;
  border: 1px solid #ccc;
  margin:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="test">
</div>

<div id="test">
</div>

<button id="btn">Click Me</button>

Upvotes: 4

Views: 7683

Answers (3)

O. Ezekiel
O. Ezekiel

Reputation: 11

$("#test:eq(1)").css("background-color","blue");

Upvotes: 1

Adil
Adil

Reputation: 148110

You must not have duplicate ids but if you can not do that you can use Attribute Equals Selector [name=”value”] with :eq(index). The :eq takes the index of element of the collection. You may also want to use background-color.

Live Demo

 $("[id=test]:eq(1)").css("background-color","blue");

Upvotes: 10

gurvinder372
gurvinder372

Reputation: 68393

Try using the data-id attribute instead since duplicate ids can produce unpredictable behaviour.

$("#btn").click(function(){      
  $("[data-id='test']:eq(1)").css("background","blue");
});
[data-id='test'] {
  height: 100px;
  width: 100px;
  border: 1px solid #ccc;
  margin:10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-id="test">
</div>

<div data-id="test">
</div>

<button id="btn">Click Me</button>

Upvotes: 1

Related Questions