Reputation: 1293
I have the following situation. I need to simulate a button click on the off value button under a div based on its id
<div id="deviceControls1">
<button value="Off">Off</button>
<button value="On" class="active">On</button>
</div>
<div id="deviceControls2">
<button value="Off">Off</button>
<button value="On" class="active">On</button>
</div
I know this is not valid code but in other words id like:
document.getElementById('deviceControls2').getElementsByValue('Off').click();
Im not sure how to use javascript to obtain this result
Upvotes: 0
Views: 1707
Reputation: 1492
You may find this link useful: Creating and triggering events - Web developer guide | MDN
For instance, to simulate click on "Tags" link in stackoverflow, you can do
var event = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true
});
var navTags = document.getElementById('nav-tags');
var canceled = !navTags.dispatchEvent(event);
this post was edited and, below was my old answer using old APIs.
You can do something like:
var event = document.createEvent("MouseEvents");
event.initEvent('click', true, true);
var element = document.getElementById('deviceControls2').getElementsByValue('Off');
element.dispatchEvent(event);
Upvotes: 0
Reputation: 16874
You've included the jQuery tag, so if you are using jQuery you can do the following:
$('#deviceControls2 > button[value="Off"]').click();
Upvotes: 1
Reputation: 27012
Using javascript, try this:
var buttons = document.getElementById('deviceControls2').getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].value == 'Off') {
buttons[i].click();
}
}
Using jQuery (since you have it tagged):
$('#deviceControls2').children('button[value="Off"]').click();
Upvotes: 1