user1901218 user1901218 - 10 months ago 47
Javascript Question

Click every button with the same class on facebook

I'm trying to play around with a Facebook group chat I made a while ago. The plain fact is I added too many people and I need to remove absolutely everyone.
This is the html of one of the buttons (they all share the same class):

<a class="_42ft _4jy0 _4jy3 _517h _51sy" role="button" href="#" ajaxify="/chat/remove_participants/?elem_id=u_32_4&amp;uid=1124361845&amp;tid=958151054268315" rel="async-post">Remove</a>

So with that, I hoped to use this here and it'd click all the buttons at once:

document.getElementById('_42ft _4jy0 _4jy3 _517h _51sy').click();

But the error message...:

VM1719:1 Uncaught TypeError: Cannot read property 'click' of null(…)

comes up.. I'm really confused as to why the click function doesn't work.


Answer Source

If you want to select DOM Tree Elements by its classname, getElementById() is not a correct option, because it selects the element by its ID. So, instead you should be choosing getElementsByClassName() which returns an array of elements with that class name. Then you can loop over the elements to click it programmatically.

var group_chat_buttons = document.getElementsByClassName('_42ft _4jy0 _4jy3 _517h _51sy');
for (i = 0; i < group_chat_buttons.length; ++i) {