Clicking all elements of a specific class in JavaScript?

console, html, javascript, web

Solution

First off, it's really not clear what you're trying to accomplish. If you can include some HTML and explain in words what you're actually trying to do, we can give you a better idea how to best solve the problem.

Then, I see several potential issues (trying to guess what you're really trying to do):

1) `document.querySelectorAll("follow js-follow btn btn-primary")` is looking for this hierarchy of tag names like this:

<follow>
    <js-follow>
        <btn>
            <btn-primary>

Is that really what you're looking for, or do you mean class names? If class names, then you need a `.` in front of the names or if you are looking for objects with ANY of these class names, then put a period in front of them and put commas between them.

2) It makes no sense to run the exact same `getElementsByClassName()` query numRepeat times. Just run it once and iterate through the results.

3) Rather than call a `click()` method, it is generally better to just execute the code you want for that DOM object and pass it the desired DOM object. You can use the same function for a click handler and calling directly if that's desired.

I suspect that issue #1 is probably your main issue as it's probably finding zero results that way you have it now.

If I assume that the selector you really want is based on looking for any object with any of these class names, then you can use this:

var items = document.querySelectorAll(".follow, .js-follow, .btn, .btn-primary");
for (var i = 0; i < items.length; i++) {
    if (items[i].getAttribute("data-following") === "0") {
        items[i].click();
    }
}

Problem

I'm new to JavaScript. I'm trying to create a script that will click all elements that belong to a specific class. My code doesn't seem to be working; I've run it through several different debugging programs that returned no results. After running it through the console, all it returned was "undefined." What can I do? Note that: the elements I would like to click are buttons; they all belong to the class "follow js-follow btn btn-primary"; I only want to click them if the data value "data-following" is equal to "0." Thanks! ``` var numRepeat = document.querySelectorAll("follow js-follow btn btn-primary").length; for (var i = 0; i < numRepeat; ++i) { var currentFocus = document.getElementsByClassName("follow js-follow btn btn-primary")[i]; if (currentFocus !== null) { var followBinary = currentFocus.getAttribute("data-following"); if (followBinary === "0") { currentFocus.click(); } } } ```

Original source