简体   繁体   中英

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> 

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");

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> 

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM