Javascript does not work in Wordpress

Asked

Viewed 396 times

1

I am running the following Javascript code on the site I made in Wordpress.

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

console.log(itens);

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

I don’t know if it helps, but this is the browser console print => https://prnt.sc/les18p2

  • I believe the problem is in importing the file. Make sure that the file is being loaded. Updates the file by adding an Alert('test') and see if it has any results

  • 1

    Try putting the code inside this event: document.addEventListener("DOMContentLoaded", function(){ CÓDIGO AQUI });... may be running the code before loading the DOM.

  • Thanks @Sam worked out with the solution you talked about, you know tell me why this problem? is it a peculiarity of Wordpress?

1 answer

2


Your Wordpress is loading the script before the full DOM upload (probably on head page). With this the code does not find the elements because they have not yet been loaded (the head comes before the body where the page visuals are located).

To resolve, add the code to the event DOMContentLoaded, because then the script will only run when the DOM is fully loaded:

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.