I’m trying to figure out why executing a click() function on an <a> tag element returns a TypeError of ‘undefined_method’. For an example, visit this page: http://http://www.google.com/#&q=test . Now, each search result on this page has a class name of ‘l’, so if I ask for:
document.getElementsByClassName('l')
I get a list of all of the search result <a> tags. Logically, indexing this array as follows gives me a specific <a> tag:
document.getElementsByClassName('l')[0]
But, what if I want to click on that link? I would expect the following to work
document.getElementsByClassName('l')[0].click()
But instead I get the TypeError ‘undefined_method’.
Why? And how would I activate this link?
thx
If you want to dispatch a click event into the DOM, you’ll have to use the W3C DOM dispatchEvent method for compliant browsers and the MS fireEvent method for others. Some browsers may not support either.
If you want to deal with HTML5 browsers, then you can call the element’s click method, however you must test for support first and don’t be surprised if browsers don’t respond. Most view programatic firing of element listeners/handlers as a bad thing.
Probably the best method in this case is as Zhehao Maoto said and set window.location property to the A element’s href, or just let the user click on the link they want and let HTML do its job.
Edit
Testing shows that IE supports click on A elements so that the click handler is fired and the link is followed (if the handler doesn’t return false). In Firefox, the handler will be called but the link won’t be followed.
In Chrome, an A element does nothing but the button responds. Opera fires the A’s click handler and follows the link. So the bottom line is that support is very patchy (not really a surprise).
e.g.