0

Trying to add a class to an element, I need to get by class name. Any idea why it is not working? (Using Wordpress Code Snippets in case someones wondering)

<?php
    add_action( 'wp_head', function () { ?>

    <script>
        var myButton = document.getElementsByClassName("menu-toggle mobile-menu");
        myButton.classList.add(".teststyle");   
    </script>

    <style>
        .teststyle {} 
    </style>

<?php } );
Mihail Minkov
  • 2,463
  • 2
  • 24
  • 41
nörde
  • 1
  • 2

2 Answers2

1

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"))
});
tobimori
  • 527
  • 2
  • 12
  • Thank you very much. This one sounds logical but for some reason the element does not get any new class. – nörde Apr 26 '21 at 19:02
  • Right. The issue is within your script placement. It will be run before the elements are added to the DOM. Check my update. – tobimori Apr 26 '21 at 20:15
0

Normally the response of a document.getElementsByClassName(...) is a NodeList. So basically you have to assign the value to a specific index of that NodeList.

In this case you should be getting an error in console that says something like

TypeError: Cannot read property 'add' of undefined

That happens because your NodeList doesn't have an element called classList and because of that the add function doesn't exist in that context.

Once you get the elements by class you get a NodeList element with all the corresponding elements and what you can do is:

myButton[0].classList.add("teststyle");

Also, here you don't need the point prefix for the class.

Here's an example.

var myButton = document.getElementsByClassName("menu-toggle mobile-menu");

console.log(myButton);

console.log(myButton[0]);

myButton[0].classList.add("test-class");
.test-class {
  color: red;
}
<button class="menu-toggle mobile-menu">Button</button>
Mihail Minkov
  • 2,463
  • 2
  • 24
  • 41