Skip to content
Advertisement

onClick event for container having duplicate IDs

I know Its weird, but the existing code I’m working have Duplicate ID’s instead of class.

<div class="67275686" id="sy_brn"><b>Some Text Goes Here 1</b></div>
<div class="1227552" id="sy_brn"><b>Some Text Goes Here 2</b></div>
<div class="4527552" id="sy_brn"><b>Some Text Goes Here 3</b></div>

i’m tying to get value of class using sy_brn ID.

expecting to get value like-

$('#sy_brn').click(function() { 
var value = $(this).attr('class');
});

its not working as multiple ID on same page not works. I don’t have the flexibility to convert all <div IDs to class.

Is there any way I can trigger click for sy_brn ID & get value of class?

Advertisement

Answer

Use querySelectorAll

const els = document.querySelectorAll("#sy_brn");
els.forEach(el => el.addEventListener("click", ev => alert(ev.currentTarget.classList)));
<div class="67275686" id="sy_brn"><b>Some Text Goes Here 1</b></div>
<div class="1227552" id="sy_brn"><b>Some Text Goes Here 2</b></div>
<div class="4527552" id="sy_brn"><b>Some Text Goes Here 3</b></div>
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement