Search code examples
javascriptfactoryqueryselector

Unable to obtain element through querySelectorAll("class") , class assigned in factory function


I created 3 buttons through factory function and assigned class "btn" to them and return the object, now I want to access all the button having class "btn" , but I am getting a empty NodeList

I want to store all the button having class "btn" in tabs variable

        const tabButton = function(name)
        {
            const button = document.createElement("button")                     // button creation
            button.innerText = name
            button.classList.add("btn")
            return {button}
        }

        const Header = function()
        {
            const homeButton = tabButton("Home").button
            const MenuButton = tabButton("Menu").button                         
            const ContactButton = tabButton("Contact").button
      
            const tabs = document.querySelectorAll(".btn")   
            console.log(tabs)  // giving NULL value
            return {tabs}
        }

Solution

  • Your tabButton function calls create the elements, but don't put them in the document anywhere. document.querySelectorAll only looks for elements that are in the document. If you put those buttons in the document, they'd be found by document.querySelectorAll, but there isn't a function that looks through every object everywhere in memory to see if it's a button that matches. There are only functions that look in documents or specific elements.

    Here's an example showing the result before and after putting those buttons in the document:

    const tabButton = function(name) {
        const button = document.createElement("button");
        button.innerText = name;
        button.classList.add("btn");
        return {button};
    };
    
    const Header = function() {
        const homeButton = tabButton("Home").button;
        const menuButton = tabButton("Menu").button;
        const contactButton = tabButton("Contact").button;
    
        console.log(document.querySelectorAll(".btn").length); // 0
        document.body.appendChild(homeButton);
        console.log(document.querySelectorAll(".btn").length); // 1
        document.body.appendChild(menuButton);
        console.log(document.querySelectorAll(".btn").length); // 2
        document.body.appendChild(contactButton);
        console.log(document.querySelectorAll(".btn").length); // 3
        const tabs = document.querySelectorAll(".btn");
        return {tabs};
    };
    
    Header();