Search code examples
javascriptqueryselector

Why Does That JS Code Not Work For Anything Except The First Class On The Page?


The following JS code turns on/off the in-site search, but there is a .search-button button in 2 places on the page, first one works but second one does not work. If I add more, they also do not work. Can I get this code to run on all classes on the page that contain a .search-button?

var wHeight = window.innerHeight;
var sb = document.querySelector(".search-button");
var closeSB = document.querySelector(".search-close");
var SearchOverlay = document.body;
var searchBar = document.querySelector(".search-bar");
// Show
searchBar.style.top=wHeight/2 +'px';
    console.log(wHeight);
    window.addEventListener("resize", function() {
        console.log(wHeight);
        wHeight = window.innerHeight;
        searchBar.style.top=wHeight/2 + 'px';
    }, true);
document.addEventListener("click", function() {
    sb.onclick = function() {
    console.log("Opened Search for Element: ");
    SearchOverlay.classList.add("show-search");
};
// Hide
closeSB.onclick = function() {
    console.log("Closed Search for Element: " + closeSB);
    SearchOverlay.classList.remove("show-search");
    };
}, true);

Solution

  • It's because you're using document.querySelector() which returns the first element matching your query. For more details check https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector.

    To query all elements with same class you need to use document.querySelectorAll() which returns all elements matching as an array. Then, you can use the array forEach() function to iterate over all elements and add event function for all.

    var sb = document.querySelectorAll(".search-button");
    
    sb.forEach(el => el.onclick = function(e) {
        console.log("Opened Search for Element: ");
        SearchOverlay.classList.add("show-search");
    });
    

    Update: You can also simplify your