如何在点击事件中获取子元素

Mat*_*Mol 3 html javascript ecmascript-6

我正在向按钮添加单击事件,并且需要获取该按钮的父级,之后我需要获取该父级的特定子级。

问题还在于我有多个这样的按钮及其相应的容器和子项。

我能够为每个按钮添加单击事件,但我似乎无法独立获取这些按钮的元素。

超文本标记语言

<div class="parentContainer">
     <div class="otherElement"></div>

     <a class="button">

     <div class="childElement"></div>
</div>
Run Code Online (Sandbox Code Playgroud)

JS

var btn = document.querySelectorAll(".button");

for (let i = 0; i < button.length; i++){
    button[i].addEventListener('click', function(){

        var container = this.closest('.parentContainer');
        var j = 0;

        for(j = 0; j < container.length; j++){ 
            if(j.classList.contains('childElement')){
                j.classList.add('Example')
            } else {
                container.style.background = "white";
            }
        };
    });
}
Run Code Online (Sandbox Code Playgroud)

对于单击的特定按钮,其兄弟元素(childElement)应该获得“Example”类。

Tom*_* O. 6

您可以通过使用事件委托技术来简化这一点- 这样您的代码只需要一个事件处理程序,而不是代码中每个“按钮”的不同处理程序。设置事件处理程序后,您可以利用DOM API来查找.otherElement相应父元素下的元素。我在您的代码中添加了几个“按钮”,以展示无论您添加多少个“按钮”,它都可以很好地工作:

const log = e => {
  console.clear();
  console.log(`${e.target.parentNode.previousElementSibling.dataset.about}`);
};
document.querySelector('.parentContainer').addEventListener('click', e => {
  if (e.target.classList.contains('childElement')) {
    e.target.classList.toggle('example');
    log(e);
  }
});
Run Code Online (Sandbox Code Playgroud)
.example {
  color: green;
  font-size: 32px;
  font-weight: bold;
}
Run Code Online (Sandbox Code Playgroud)
<div class="parentContainer">
  <div class="otherElement" data-about="This is otherElement for Button 1"></div>
  <a class="button">
    <div class="childElement">Button 1</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 2"></div>
  <a class="button">
    <div class="childElement">Button 2</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 3"></div>
  <a class="button">
    <div class="childElement">Button 3</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 4"></div>
  <a class="button">
    <div class="childElement">Button 4</div>
  </a>
  <div class="otherElement" data-about="This is otherElement for Button 5"></div>
  <a class="button">
    <div class="childElement">Button 5</div>
  </a>
</div>
Run Code Online (Sandbox Code Playgroud)