Melisa
Melisa

Reputation: 422

Uncaught TypeError: Cannot read property 'add' of undefined on localhost - Wordpress

I want to add a class in a div but that is not working.

PHP - JS

function wpb_hook_javascript() {
    if (is_page ('50')) { 
      ?>
          <script type="text/javascript">
            // your javscript code goes here
            window.addEventListener("load", ()=>{
            console.log("HELLO");
            document.getElementById("all-categories").classList.add("mystyle");
            });
          </script>
      <?php
    }
}

add_action('wp_head', 'wpb_hook_javascript');

HTML

<div class="dropdown-categories collapse " id="all-categories">

DEVTOOLS

enter image description here

Upvotes: 0

Views: 116

Answers (1)

Dillan Wilding
Dillan Wilding

Reputation: 1111

Have you tried splitting this line

document.getElementById("all-categories").classList.add("mystyle");

Into two lines to confirm the element exists, it's only one element, and has classList property?

var categories = document.getElementById("all-categories");
console.log(categories);
console.log(categories.classList); // I suspect this is undefined, thus .add() function doesn't exists
categories.classList.add("mystyle");

Upvotes: 1

Related Questions