Chrome Console Javascript "Cannot read property 'click' of undefined"

3k views Asked by At

I have been trying to create a script that favorites all of the items in an etsy store

var buttons = document.getElementsByName('favorite-container');
for(var i = 0; i <= buttons.length; i++)  
buttons[i].click();

However I get this error when I try and run the script in the developer console in Chrome

"Uncaught TypeError: Cannot read property 'click' of undefined at :3:11"

Am I right in thinking that this should work? I don't know of an alternative for running Javascript on a website that I am logged into apart from getting into automation tools like selenium


In response to first comment

<div class="favorite-container" data-listing-id="547704515">
    <button type="button" class="btn-fave done" data-source="casanova-shop-featured" aria-pressed="true">
        <!--icon font and display:none; elements -->
        <span aria-hidden="true" class="icon"></span>
        <span class="screen-reader-only default">
            Favourite
        </span>
        <span class="screen-reader-only done remove">
            Favourited
        </span>
        <span class="ie-fix">&nbsp;</span>
    </button>
</div>

1

There are 1 answers

1
Matheus Cuba On

You are using the Wrong method to get Elements, try document.getElementsByClassName

var buttons = document.getElementsByClassName("favorite-container");
for(var i = 0; i < buttons.length; i++)  {
    buttons[i].click();
}

Or you could use JQuery like this:

$(".favorite-container").each(function(){
    $(this).click();
});