0

I have functions.php file which contains function which correctly get js file to my website, but when I try use querySelector('any selector name') then that function return null

I try use querySelector("html") and then I receive all my html code but in any other cases I get value of null

footer.php file

<?php wp_footer(); ?>
</body>
</html>

functions.php file

<?php

function university_files() {

  wp_enqueue_style('custom-google-fonts', '//fonts.googleapis.com/css?family=Lato:100,300,400,700');
  wp_enqueue_style('custom-google-fonts', '//fonts.googleapis.com/css?family=Merriweather:300,400,700');
  wp_enqueue_style('university_main_styles', get_stylesheet_uri());
}

add_action('wp_enqueue_scripts', 'university_files');

function remove_admin_login_header() {
    remove_action('wp_head', '_admin_bar_bump_cb');
}
add_action('get_header', 'remove_admin_login_header');
?>

header.php

<!DOCTYPE html>
<html lang="pl">

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
</head>

<body>
    <button class="hamburger"></button>
    <header>
        <nav>
            <ul class="nav">
                <li class="navel"> <a href="/">o firmie</a> </li>
                <li class="navel"> <a href="/oferta">oferta</a> </li>
                <li class="navel"> <a href="/galeria">galeria</a> </li>
                <li class="navel"> <a href="/kontakt">kontakt</a> </li>
            </ul>
        </nav>
    </header>

script.js

const header = document.querySelector('header');
const menu = document.querySelector('.hamburger');


menu.addEventListener("click", ()=>{
menu.classList.toggle("active");
header.classList.toggle("active");
});
  • 1
    where are you using querySelector? My guess in the head and you are not waiting for document.ready or window.onload – epascarello May 06 '19 at 12:26
  • https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – epascarello May 06 '19 at 12:36

1 Answers1

0

You need to call your script into DOMContentLoaded if your script is inserted into head not before of closing body tag.

document.addEventListener('DOMContentLoaded', function () {
  const header = document.querySelector('header');
  const menu = document.querySelector('.hamburger');


  menu.addEventListener("click", ()=>{
  menu.classList.toggle("active");
  header.classList.toggle("active");
});
})
Radonirina Maminiaina
  • 6,515
  • 4
  • 29
  • 54