Reputation: 2924
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
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();
});
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
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
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