简体   繁体   中英

select elements with same id and different attribute jquery

I have a list ul where at least two rows has the same id but with a different attribute value id-type

CODE TRIED

In this code I only outline both rows (same Id), how can I fix this?

 $("button").on("click",function(){ $("ul").find("li#post1").css("border","5px solid red"); });
 li{margin:5px 0;}
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <ul> <li id='post1' id-type='1'> I dont want to be selected</li> <li id='post1' id-type='2'> I want to be selected only</li> <li id='post3' id-type='2'> text</li> <li id='post2' id-type='2'> text</li> </ul> <button>elegir id='post1' id-type='2'</button>

IDs are supposed to unique in DOM. So, you can change all ids to class instead and then you can access id-type='2' element easily like:

 $("button").on("click", function() { $("ul").find("li.post1[id-type='2']").css("border", "5px solid red"); });
 li { margin: 5px 0; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script> <ul> <li class='post1' id-type='1'> I dont want to be selected</li> <li class='post1' id-type='2'> I want to be selected only</li> <li class='post3' id-type='2'> text</li> <li class='post2' id-type='2'> text</li> </ul> <button>elegir id='post1' id-type='2'</button>

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