JavaScript does not work in WordPress

1

I'm running the following JavaScript code on the site I made in WordPress.

var itens = document.querySelectorAll('h1');

console.log(itens);

I am pulling from a file that is in the js folder, but it does not bring the items from h1, but if I run that same code above in the browser console it works. Can anyone tell me what I might be doing wrong?

I do not know if it helps, but this is the browser's console print = > link

    
asked by anonymous 06.11.2018 / 15:59

1 answer

2

Your Wordpress is loading the script before full load of the DOM (probably in head of the page). So the code does not find the elements because they have not yet been loaded ( head comes before the body where the visual elements of the page are).

To solve, add the code in the DOMContentLoaded event, because the script will only run when the DOM is fully loaded:

document.addEventListener("DOMContentLoaded", function(){
   var itens = document.querySelectorAll('h1');
   console.log(itens);
});
    
06.11.2018 / 18:30