I have a page with a few links that are all like this:
<a href="/" class="answer-item" rel="0">10</a>
I would like to use the click() function to simulate a user’s click on one of them, but it doesn’t seem to work in my tests.
//Evaluate a mathematical expression from another part of the page
var numberAnswer = eval(document.getElementById("question-title").getElementsByTagName("b")[0].innerHTML);
//Builds an array with the links that may match the expression
var choices = document.getElementsByClassName('answer-item');
//Iterates through array to find a match then clicks it
for(var i in choices){
if(choices[i].innerHTML == numberAnswer){
choices[i].click();
break;
}
}
I’m sure that choices[i] is the correct element.
Firefox does nothing, Opera does nothing, and click() is not available in Chrome (I think).
Also, I have tried to use dispatchEvent() in this form:
var evt = document.createEvent('MouseEvents');
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
choices[i].dispatchEvent(evt);
This apparently returned true in Firefox and Chrome but did not change anything.
The most bothersome part is that a link with only the href attribute works fine with .click().
EDIT
Per discussion in the comment area, it seems that the behavior used in this answer is non-standard, or at least not consistent across user-agents. I am researching this issue further; if you use the information in this answer, please carefully check your code in all browsers to ensure it works as expected.
EDIT 2
Per the comment from the OP, there is a “just make it happen” approach that would work here. It has some downsides, namely that your bound events cannot call
preventDefault— this method will not respect it. You could build some kind of event wrapper that might be able to deal with this… anyway, here’s the code and fiddle:HTML:
Script:
jsFiddle: http://jsfiddle.net/CHMLh/
Original answer
Your sample code is incomplete. If I take just the basics, it works correctly:
jsFiddle: http://jsfiddle.net/cgejS/
I would re-evaluate your assumptions that you’re dealing with the correct dom element.
On an unrelated note, this:
… what?
evalis evil — if you’re ever using it for any reason, question whether you have the right approach. Are you trying to get an integer out of a string? SeeparseInt(docs), the right tool for this job: