Given this HTML:
<ul class="myList">
<li class="List" data-pos="Noah">
<label><input class="text">pass</label>
</li>
<li class="List" data-pos="Liam">
<label><input class="text">fail</label>
</li>
<li class="List" data-pos="James">
<label><input class="text">average</label>
</li>
</ul>
I want to create a JavaScript function that will add new class to an element when the user clicks on it, based on the data-pos attribute of the element.
click on "Noah" add class Noah1
click on "Liam" add class Liam1
click on "James" add class James1
Expected result after clicking all the elements:
<ul class="myList">
<li class="List Noah1" data-pos="Noah">
<label><input class="text">pass</label>
</li>
<li class="List Liam1" data-pos="Liam">
<label><input class="text">fail</label>
</li>
<li class="List James1" data-pos="James">
<label><input class="text">average</label>
</li>
</ul>
I tried the following javascript. It results in <label class="null1"> instead of <li class="List Noah1"> or <li class="List Liam1"> or <li class="List James1">
function clickEvent(event) {
event.target.classList.add(event.target.getAttribute('data-pos') + "1")
console.log(event.target.classList)
}
document.querySelector('ul').addEventListener('click', clickEvent, false);
const target = event.target.closest('li');at the beginning of the click handler, and usetargetinstead ofevent.targetin the later code. Notice also, that you've to remove the harcoded "name classes". This way you can click what ever element inside a list element, and the code will find the closest list element in the parent chain. It's also good to check, thattargetwas actually found, otherwise the code will trigger an error, if you've somehow managed to click outside of an list element but still inside the ul.