如何找到 e.target 的 parents 及其 children。并移动一个 'active class'

How to find parents of e.target and their children. And move a 'active class'

此代码是关于 'active' 按钮的事件。我必须在全球范围内使用此代码。但它与所有具有 btn class.

的元素冲突

所以我想在点击btn(按钮)时给出一个激活的class。而当我点击btn的时候,我想找到e.target的parents,找到他们的children,然后移动一个'active class'。我想在全球范围内使用此代码。但是我的代码不起作用。因为它无法准确找到 e.target 的 parents。还有其他好的方法吗?

var btns = document.querySelectorAll('.btn');
  [].forEach.call(btns, function (item) {
    item.addEventListener('click', function (e) {
      var selectedParent = e.target.parentNode;
      var selected = selectedParent.querySelectorAll('.btn.active');
      if (selected.length > 0) {
        selected[0].className = selected[0].className.replace(' active', '');
        item.className += ' active';
      }
    });
  });

可能会将 e.target 替换为 e.currentTarget 或者 item.parentNode 也可以。

如果你的按钮都在同一个父元素下,那么你可以这样做(我添加了一个.active class只是为了展示效果):

var btns = document.querySelectorAll('.btn');
[].forEach.call(btns, function(item) {
  item.addEventListener('click', function(e) {
    var selectedParent = e.target.parentNode;
    var childBtns = selectedParent.children;
    for(var i = 0; i < childBtns.length; i++) {
      childBtns[i].classList.remove("active");
      this.classList.add("active");
    }
  });
});
.active {
  background: #F55;
}
<button class="btn">Button 1</button>
<button class="btn">Button 2</button>
<button class="btn">Button 3</button>
<button class="btn">Button 4</button>
<button class="btn">Button 5</button>

编辑:实际上即使按钮不在同一个父项下也能正常工作。