I checked other questions which are similar but they are all having mistakes in the code.
This is a different case. The jQuery part in this code is working fine but if I work with the vanilla js, the click event is not triggered and no console error detected. The script is run at the bottom of the body after the elements are loaded.
//jQuery - this works
const openSearchButton = $(".js-search-trigger");
openSearchButton.on("click", () => console.log("hello"));
//Vanilla JS - this does not
const openSearchButton = document.querySelector(".js-search-trigger");
openSearchButton.addEventListener("click", () => console.log("Hello"));
querySelector
only acts on the first matching element:
const openSearchButton = $(".js-search-trigger");
openSearchButton.on("click", () => console.log("jquery"));
//Vanilla JS
const openSearchButtonTwo = document.querySelector(".js-search-trigger");
openSearchButtonTwo.addEventListener("click", () => console.log("vanilla"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="js-search-trigger">Button one</button>
<button class="js-search-trigger">Button two</button>
From comments, you have another (hidden) element on the page with the same class, so need to use querySelectorAll instead.
jQuery automatically iterates over the whole list of results for you, but in vanilla you have to do that explicitly:
const openSearchButtons = document.querySelectorAll(".js-search-trigger");
[...openSearchButtons].forEach(button => {
button.addEventListener("click", () => console.log("all vanilla"));
})
<button class="js-search-trigger">Button one</button>
<button class="js-search-trigger">Button two</button>