I am a bit confused. Consider this case : I have a list of checkboxs, each one having an id, class and data-attribute (called data-uid, which is not equal to the checkbox id).
The point is to retrieve the clicked checkbox data-uid attribute.
So I use a JS click event on the checkboxs parent, to determine which one was clicked and get its data-uid.
People have told me to use a loop until I get the checkbox I clicked, like this (I could have used a normal for loop but you get the point) :
const checkboxArray = [...document.getElementsByTagName('input')];
document.addEventListener('click', event => {
checkboxArray.find(element => {
if (event.target === element) {
console.log(element.getAttribute('data-uid'));
}
});
});
However, why not just do it this way, without any loop ?
document.addEventListener('click', event => {
if (event.target.getAttribute('data-uid')) {
console.log(event.target.getAttribute('data-uid'));
}
});
Those two methods return the expected result : the data-uid attribute of the clicked checkbox. However, which one is the best to use and why ? As I said before, people always told me to use loops, but why if you can avoid it ?
Here is a snippet to see it in action :
const method1 = document.getElementById('method1');
const method2 = document.getElementById('method2');
const output1 = document.getElementById('output1');
const output2 = document.getElementById('output2');
method1.addEventListener('click', event => {
const checkboxArray = [...document.getElementsByClassName('checkbox')];
checkboxArray.find(element => {
if (event.target === element) {
output1.innerHTML += `${element.getAttribute('data-uid')} `;
}
});
});
method2.addEventListener('click', event => {
if (event.target.getAttribute('data-uid')) {
output2.innerHTML += `${event.target.getAttribute('data-uid')} `;
}
});
<div id="method1">
<p><strong>Method 1 : Using a loop</strong></p>
<label for="1">1</label>
<input type="checkbox" data-uid="a1" class="checkbox">
<label for="2">2</label>
<input type="checkbox" id="2" data-uid="b2" class="checkbox">
<label for="3">3</label>
<input type="checkbox" id="3" data-uid="c3" class="checkbox">
</div>
<div id="output1">Data uid : </div>
<br>
<div id="method2">
<p><strong>Method 2 : Not using a loop</strong></p>
<label for="4">4</label>
<input type="checkbox" id="4" data-uid="d4" class="checkbox">
<label for="5">5</label>
<input type="checkbox" id="5" data-uid="e5" class="checkbox">
<label for="6">6</label>
<input type="checkbox" id="6" data-uid="f6" class="checkbox">
</div>
<div id="output2">Data uid : </div>
Thank you very much for taking the time to read and enlighten me.
Tom