I have this javascript code which does not run in the form of bookmarklet. What the code do is it selects all the elements with the class "btn" and clicks on it using javascript's click() function. The code is:
javascript:(
function(){
alert('started');
var tn = document.getElementsByClassName('btn');
for (var i=0;i<tn.length; i++) {
tn[i].click();
}
alert('ended');
}
)
()
And I am testing it on-
<button class="btn" onclick="alert('1')">Click</button>
<button class="btn" onclick="alert('2')">Click</button>
<button class="btn" onclick="alert('3')">Click</button>
<button class="btn" onclick="alert('4')">Click</button>
The first and last alert (stated and ended) are shown but the html buttons are not even clicked because i see no alerts. Chrome console is showing no errors.
pasting this code at the end of the body works as expected :
</script>
alert('started');
var tn = document.getElementsByClassName('btn');
for (var i=0;i<tn.length; i++) {
tn[i].click();
}
alert('ended');
</script>
I believe there is something horribly wrong in my code like syntax or formatting or some silly mistake that I am not able to figure out on my own till now.
NOTE: I have not much experience with javascript and I am messing around with it for 2 months so pls excuse my stupidity.
Check if document.getElementsByClassName('btn') returns any elements. May be you have a problem in your test setup.