Search code examples
javascriptonloadonload-eventselectors-api

QuerySelectorAll not working when put in an external js file


When I put this code:

window.onload = function(){
    var inputs = document.querySelectorAll("input[type=text]");
    console.log(inputs.length);
    for(var j=0; j<inputs.length; j++){
        inputs[j].onclick = function(){
            this.style.width = "500px";
        }
    }
}

Into an html page, it works great, but if I put it into an external .js file the for loop never starts as inputs.length is equal to 0, even if in the page that calls the script there are plenty of inputs. What could be the problem?

Update: I found out that the code works in normal conditions, but it doesn't:

  • on inputs that are contained in a div that was previously hidden and then was shown via js my bad, the hidden input was of type "email"
  • on every input if they're loaded via ajax I found out why: since the function is fired only when the window loads, it won't see the loaded inputs

Solution

  • With the help of the users who commented/answered, I found out that some of the inputs I was trying the code to were of type "email" and not "text", while in other cases the inputs were loaded via ajax, so after the DOM was loaded. To fix these problems, I've edited

    var inputs = document.querySelectorAll("input[type=text]");
    

    To

    var inputs = document.querySelectorAll("input[type=text],input[type=email]");
    

    And I called again the function when the content loaded via ajax was ready.