AnonDCX
AnonDCX

Reputation: 2597

click() method working for link but not for button in Javascript

I have written a script that I run through dev tools -> console in chrome that auto adds comments instead of writing and submitting one at a time:

 /**
 * Created by keilc on 2/09/2015.
 */
var leaveComment = document.getElementsByClassName('plain leaveComment');
var commentBox = document.getElementsByClassName('botmarg5px feedbacktextarea');
var submit = document.getElementsByClassName('siteButton bigButton');
var comment = "thankyou very much :)";


for(var i = 0; i <= leaveComment.length; i++)
{
    // Click 'leave comment'
    leaveComment[i].click();

    // Leave comment
    commentBox[i].value = comment;

    // Submit the comment
    submit.click();
}

enter image description here

The click(); event gets called successfully for each item in the leaveComment array but when it reaches the submit buttons the click(); method fails and returns Object doesn't support property or method 'click':

enter image description here

So I tried moving the click(); call on the submit buttons outside the for loop:

for(var i = 0; i <= leaveComment.length; i++)
{
   // Click 'leave comment'
   leaveComment[i].click();

   // Leave comment
   commentBox[i].value = comment;
}

// Submit the comment
    submit.click();

but this give me Unable to get property 'click' of undefined or null reference error.

After trying these different approaches I am confused as to why the click(); method is working for the 'leave comment' link but not the submit button.

Upvotes: 1

Views: 86

Answers (2)

user2575725
user2575725

Reputation:

Problem is submit is NodeList, you need to give index as you did for leaveComment:

submit[i].click();

Upvotes: 0

Tushar
Tushar

Reputation: 87233

getElementsByClassName() returns a NodeList of all the matched elements.

Returns an array-like object of all child elements which have all of the given class names. When called on the document object, the complete document is searched, including the root node. You may also call getElementsByClassName() on any element; it will return only elements which are descendants of the specified root element with the given class names.

var submit = document.getElementsByClassName('siteButton bigButton');

If you've only one button matching classes use

submit[0].click();

If you've multiple elements, then iterate over them

for(var i = 0; i < submit.length; i++) {
    submit[i].click();
}

Upvotes: 1

Related Questions