I\'m a total newbie with JS, and I\'m trying to click on this button:
find
You need to use the method click rather than submit
. You can use submit when you want to submit a form.
getElementsByClassName
also returns an array of elements, you need to retrieve the one you want and then call click
on it.
document.getElementsByClassName('simplebutton')[0].click();
http://jsfiddle.net/kLDde/
Here is a complete script that does that. It uses jQuery for the :contains() selector.
Update: Modified script to account for reported AJAX.
// ==UserScript==
// @name _Click on a specific link
// @include http://YOUR_SERVER.COM/YOUR_PATH/*
// @require http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @require https://gist.github.com/raw/2625891/waitForKeyElements.js
// @grant GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a major design change
introduced in GM 1.0.
It restores the sandbox.
*/
//--- Note that contains() is CASE-SENSITIVE.
waitForKeyElements ("a.simplebutton:contains('follow')", clickOnFollowButton);
function clickOnFollowButton (jNode) {
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
}
Note: in some cases the contains()
term can trigger falsely. For example, if there is an <a class="simplebutton">unfollow</a>
button.
Here's one way to prevent false clicks. Modify the clickOnFollowButton
function like so:
function clickOnFollowButton (jNode) {
if ( ! /^\s*follow\s*$/i.test (jNode.text() ) ) {
/*--- If the node contains anything but "follow" (surrounded by
optional whitespace), don't click it.
*/
return false;
}
var clickEvent = document.createEvent ('MouseEvents');
clickEvent.initEvent ('click', true, true);
jNode[0].dispatchEvent (clickEvent);
}
Several things:
getElementsByClassName() returns a list or "collection" of elements. You can't just .submit()
its result like that. .submit()
is for single elements.
Since this is a link .submit()
won't work. .click()
will often work, but often not -- when a link is empowered by an event listener (which must be the case for this question).
The clickEvent
code, given above, works in almost all cases.
The page code you gave does not have any link, with class="simplebutton"
and text containing find
!
What Browser are you using? Which Greasemonkey version? And what OS?
Find and use an appropriate javascript reference and an appropriate DOM reference. The reference listed in the question is for a library that is not standard and not included in your script (most likely).
Use the CSS path, its much easier than XPATH, for this kind of thing. Firebug will show you the CSS path for a given element.
jQuery uses CSS selectors/paths, as does document.querySelector()
(a non jQuery approach).