Search code examples
javascriptselectors-api

querySelectorAll not working for specified elements


I'm trying to achieve to select all specified elements that i want using looped querySelectorAll but I'm still failing. Only the first element is always selected. Here is my code:

HTML:

<div id="text">Text 1</div>
<div id="text">Text 2</div>
<div id="text">Text 3</div>


JS:

function query(selector) {
    var elem = document.querySelectorAll(selector);

    if(elem.length) {
        for(var i = 0; i < elem.length; i++) {
            return elem[i];
        }
    }
}

query("#text").style.background = "red";


What have I done wrong?


Solution

  • The return statement terminates the function execution, i.e. the subsequent code is not executed. Your function returns the first selected element in the first iteration of the loop and that's the end of it.

    In this case there is no need to iterate the collection. If you want to get all the selected elements you can return the returned value of the querySelectorAll method, but then you can't use the style property that way as the returned collection doesn't have such property.

    function query(selector) {
        // convert the NodeList into a regular array
        // https://developer.mozilla.org/en-US/docs/Web/API/NodeList
        return Array.prototype.slice.call(document.querySelectorAll(selector));
    }
    
    // since `query` returns an array you can use it's `forEach` method 
    // for iterating over the array
    query(".text").forEach(function(el) {
       el.style.backgroundColor = "red";
    });
    

    Note that IDs must be unique. You should use classes instead.