简体   繁体   中英

Want to add a CSS class to an element when it is clicked

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);

You have nested elements. The click event fires on the inner element ( label ) and then bubbles up to the ul element.

You need to step to the parent element if the label receives the click.

function clickEvent(event) {
  let element = event.target
  if(element.tagName === 'LABEL') {
    element = event.target.parentElement;
  }
  element.classList.add(element.getAttribute('data-pos') + "1")
  console.log(element.classList)
}

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