Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

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

This code is about event of 'active' button. I have to use this code globally. But it conflicts with all the elements that have the btn class.

So I want to give an active class when I click on btn (button). And when I click on the btn, I want to find the parents of e.target, find their children, and move a 'active class'. And I want to use this code globally. But my code is not working. Because It can't find parents of e.target exactly. Is there any other good way?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your buttons are all under the same parent element, then you can do it this way (I have included an .active class just to show the effect):

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...