You're querying for multiple elements, as class names are not unique, therefore you need to loop through them. Also, you don't need the selector-specific dot to specify a class when using classList.add
.
This snippet should work, if your element has both the classes menu-toggle
and mobile-menu
:
document.querySelectorAll(".menu-toggle.mobile-menu").forEach((element) => element.classList.add("teststyle"))
If the element with the class mobile-menu
is a child of the element with the class menu-toggle
, try this:
document.querySelectorAll(".menu-toggle.mobile-menu").forEach((element) => element.classList.add("teststyle"))
Edit:
As you're adding the script into the head, it'll be run before the HTML elements are loaded, so you need to defer the execution until the DOM is loaded.
You can either add the script after the elements in the DOM, or use the DOMContentLoaded event, e.g. like this:
window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll(".menu-toggle.mobile-menu").forEach((element) => element.classList.add("teststyle"))
});