简体   繁体   中英

Target a specific element inside of the div that was click without using jQuery

I have a list of items in which I would like to listen for which item was clicked on and change the CSS for an inner div in that item.

var inactiveItems = document.getElementsByClassName('inactive');

for (var i = 0; i < inactiveItems.length; i++) {
  inactiveItems[i].addEventListener('click', handleClick, false);
}

function handleClick(e) {
  var width = document.body.clientWidth;
  console.log(e.target);
  if (width < 960) {
    e.target.style.top = '0px';
  }
}

Here is my HTML:

<li class="days_item days_item inactive"">
  <span>19</span>
  <div class="locked-item"></div>
</li>

I would like to change the CSS on the .locked-item inside the event target, not the target itself.

Rather than accessing e.target (which is the clicked element), access e.currentTarget in order to get the element that the event listener was originally attached to. Then you can select the child .locked-item by chaining .querySelector('.locked-item') :

Example Here

function handleClick(e) {
    var width = document.body.clientWidth,
        day = e.currentTarget,
        lockedItem = day.querySelector('.locked-item');

    if (width < 960 && lockedItem !== null) {
        lockedItem.style.top = '0px';
    }
}

One way to do this is to use this.getElementsByClassName('locked-item')[0] to select that <div> .

 var inactiveItems = document.getElementsByClassName('inactive'); for (var i = 0; i < inactiveItems.length; i++) { inactiveItems[i].addEventListener('click', handleClick, false); } function handleClick(e){ var width = document.body.clientWidth; console.log(e.target); if (width < 960) { e.target.style.top = '0px'; } this.getElementsByClassName('locked-item')[0].style.background = 'yellow'; } 
 <li class="days_item days_item inactive"> <span>19</span> <div class="locked-item">x</div> <!-- I added some text, just so you see the div --> </li> 

Read up:

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