Home > OS >  Click on next element in javascript
Click on next element in javascript

Time:01-25

I have multiple same containers and each one contains same anchors like:

<div>
  <a href="#" >Button 1a</a>
  <a href="#" >Button 2a</a>
</div>
<div>
  <a href="#" >Button 1b</a>
  <a href="#" >Button 2b</a>
</div>
<div>
  <a href="#" >Button 1c</a>
  <a href="#" >Button 2c</a>
</div>

What I try to achieve is when I click on .button1 should start trigger and auto click on closest .button2

My js code now looks like:

const btn = document.querySelectorAll('.button1')

btn.forEach(function(btn) {
    btn.addEventListener("click", function() {
         console.log(this.innerText)
       this.closest('.button2').click()
    });
});

And here is fiddle: https://jsfiddle.net/4nhvtao1/4/

CodePudding user response:

try this

const btn = document.querySelectorAll('.button1');

btn.forEach(function(btn) {
  btn.addEventListener("click", function() {
    console.log(this.innerText);
    let current = this;
    while (!current.classList.contains("button2")) {
      current = current.parentElement;
    }
    current.click();
  });
});

CodePudding user response:

closest moves up the dom hierarchy to try to find the selector you specify. It would be better to use the sibling (~) selector (or you can just use node.nextElementSibling in this case)

const btn = document.querySelectorAll('.button1')

btn.forEach(function(btn) {
    btn.addEventListener("click", function() {
//         console.log(this.innerText)
      //var other = this.nextElementSibling;
      var other = this.parentNode.querySelector(".button1 ~ .button2")
      console.log(other);
    });
});
<div>
  <a href="#" >Button 1a</a>
  <a href="#" >Button 2a</a>
</div>
<div>
  <a href="#" >Button 1b</a>
  <a href="#" >Button 2b</a>
</div>
<div>
  <a href="#" >Button 1c</a>
  <a href="#" >Button 2c</a>
</div>

CodePudding user response:

Although I don't really understand the purpose of this, here is an approach...

btn.forEach(button => {
   button.addEventListener('click', (e) => {
      console.log(e.currentTarget.innerText)
      e.currentTarget.nextElementSibling.click()
   })
});
  • Related