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

Viewed 6631

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>

3 Answers
Related