I have a code like this:
<div >
<button id="chamad6">D6</button>
<button id="chamad20">D20</button>
<button id="chamad8">D8</button>
<button id="chamad10">D10</button>
<button id="chamad4">D4</button>
<button id="chamad12">D12</button>
</div>
Then there is another button, and I want to make a function that when its clicked it clicks in every button inside ".menuMesa". How can I do it?
CodePudding user response:
Use .click
function:
document.querySelectorAll(".chamad").forEach(e => {
e.onclick = function() {
console.log("clicked: " e.id);
}
});
document.querySelector("#clickall").onclick = function() {
document.querySelectorAll(".chamad").forEach(e => e.click())
}
<div >
<button id="chamad6">D6</button>
<button id="chamad20">D20</button>
<button id="chamad8">D8</button>
<button id="chamad10">D10</button>
<button id="chamad4">D4</button>
<button id="chamad12">D12</button>
</div>
<button id="clickall">
Click All.
</button>
CodePudding user response:
You could do it like this:
- with
querySelector
&querySelectorAll
with listening onclick_event
document.querySelector('.clickAll').addEventListener('click', () => {
document.querySelectorAll('.chamad').forEach(div => {
div.click();
})
})
//just for demo
function popup(x){
alert('you\'ve clicked on ' x);
}
<div >
<button onclick='popup("you clicked on D6")' id="chamad6">D6</button>
<button onclick='popup("you clicked on D20")' id="chamad20">D20</button>
<button onclick='popup("you clicked on D8")' id="chamad8">D8</button>
<button onclick='popup("you clicked on D10")' id="chamad10">D10</button>
<button onclick='popup("you clicked on D4")' id="chamad4">D4</button>
<button onclick='popup("you clicked on D12")' id="chamad12">D12</button>
</div>
<hr>
<button class='clickAll'>click on All divs</button>
CodePudding user response:
You do that you can use html button
attribute — onclick
So first you need to create a script tag, and then we have a function called buttonClicked
( you can rename it with any name ) and then set the onclick attribute to “buttonClicked”
So your code might be like this:
<div >
<button id="chamad6" onclick=“click(‘D6’)”>D6</button>
<button id="chamad20" onclick=“click(‘D20’)”>D20</button>
<button id="chamad8" onclick=“click(‘D8’)”>D8</button>
<button id="chamad10" onclick=“click(‘D10’)”>D10</button>
<button id="chamad4" onclick=“click(‘D4’)”>D4</button>
<button id="chamad12" onclick=“click(‘D12’)”>D12</button>
<button onclick=“clickAll()”>Click To Click All</button>
</div>
<script>
function click(id){
console.log(“You clicked “ id)
}
function clickAll(){
Array.from(document.querySelectorAll(“.chamad”)).forEach((item) => { item.click(); })
}
</script>