Konstantinos Natsios
Konstantinos Natsios

Reputation: 2924

Javascript click button function under certain div

This is the code of a button in one html page

<a class="btn" role="button" href="#">Click me</a>

I have this javascript code to click a button with a certain class

var clickBtn = document.getElementsByClassName('btn'); 
for(var i=0;i<clickBtn.length;i++)
{ 
clickBtn[i].click(); 
} 

This code clicks every button with the class "btn" in ALL the page. But there are some other buttons in the same page with the same class. So i want my javascript code to be modifided to click only a certain button in a certain div.

The code with the div is

<div class="inside">
<span>
<a class="btn" role="button" href="#">Click me</a>
</span>
</div>

Any idea of how can i modify my javascript code to click only the button inside that div?? Thanks for your time.

Upvotes: 0

Views: 788

Answers (3)

baao
baao

Reputation: 73241

You can use querySelectorAll()

Array.from(document.querySelectorAll('.inside  .btn')).forEach(btn => {      
   alert(btn.innerHTML)
   btn.click();
});

Or without es6:

[].slice.call(document.querySelectorAll('.inside  .btn')).forEach(function(btn) {
    alert(btn.innerHTML)
    btn.click();
});

DEMO

Updated for your comment (Can you update your code that if there is an id in the span like not to click the button?):

[].slice.call(document.querySelectorAll('.inside  .btn')).forEach(function(btn) {

    if (btn.parentNode.id != 'clicked') {
        alert(btn.innerHTML);
        btn.click();
    }

});

or you can use querySelectorAll() with a :not condition to avoid the if check:

Array.from(document.querySelectorAll('.inside span:not([id="clicked"]) .btn'))
    .forEach(btn => {
        alert(btn.innerHTML)
        btn.click();
    });

Upvotes: 2

Rupesh P
Rupesh P

Reputation: 70

var parentDiv = clickBtn[i].parentNode;

var clickBtn = document.getElementsByClassName('btn'); 
for(var i=0;i<clickBtn.length;i++)
{ 
var parentDiv = clickBtn[i].parentNode;
  if(parentDiv == yourDiv)
   {
    clickBtn[i].click(); 
   } 
}

I am not sure, var parentDiv = clickBtn[i].parentNode will work. But the idea is the same.

Upvotes: 0

jazmit
jazmit

Reputation: 5410

If you want a non-jQuery solution, you can use getElementById to get the div, and then getElementsByClassName to get all the buttons within that div.

var insideDiv = document.getElementById("inside");
var buttonsInsideDiv = insideDiv.getElementsByClassName();

Upvotes: 1

Related Questions