1

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>
max
  • 97
  • 6
  • 2
    You can't have 2 elements with the same id as ids have to be unique, otherwise your HTML is not valid. You can use classes instead. – matthias_h Apr 29 '20 at 17:26
  • 1
    Note that an [ID](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) "must be unique in the whole document". Also see [Does ID have to be unique in the whole page?](https://stackoverflow.com/questions/9454645/does-id-have-to-be-unique-in-the-whole-page) – showdev Apr 29 '20 at 17:27
  • 1
    Technically "cannot" should be "should not", but I completely agree. – Taplar Apr 29 '20 at 17:28
  • @matthias_h ok, i can fix that right away, but the question is how should I make my code work? – max Apr 29 '20 at 17:29
  • 1
    @max The answer is already given :) – matthias_h Apr 29 '20 at 17:33

1 Answers1

4

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>
palaѕн
  • 72,112
  • 17
  • 116
  • 136