I trying to have a javascript function to click all divs that has an id of ‘divResults’ in my form but apparently it doesn’t work, no errors but nothing buldges. Please advice. Thanks.
<a href="javascript:clickAllDivs()">Expand All</a> | <a href="javascript:clickAllDivs()" >Collapse All</a>
JavaScript :
function clickAllDivs() {
var els = document.getElementsByTagName('div');
var i = els.length; while (i--)
if (els[i].id == 'divResults' ) {
//alert("I am in"); //Check if div is eating this function
els[i].click();
}
}
Well there are a couple of problems, first, you should have only one element with an id of divResults in your page, ids are unique.
To find an element with a particular id, you can do:
If you want more elements, try using a class, and checking by
classNamein your loop, like:Second, calling
els[i].click();means that you have setted a property on that element with the name of click and assigned it a function.If you had done that, then the code is right, if not check how are you binding the event, for example if you’re doing
then you should do
You can also use jQuery for doing this in a really simple way, info here