javascript - js to communicate with dom in wordpress
one text
Solution:
The issue is not with "Wordpress structure", but because you're loading the script in <head>
, but attempting to access elements in the document body before waiting for the DOM to be ready.
<script>
tags in the <head>
will be downloaded and executed, before the browser parses the rest of the HTML found after <head>
This causes issues with your selectors since when the script is executed, those elements that would have matched your selectors do not exist in the DOM tree at runtime:
Source: https://www.growingwiththeweb.com/2014/02/async-vs-defer-attributes.html
There are two solutions:
- Ensure that
script.js
is loaded in the footer, which means the DOM has been parsed and is ready, or - Wrap all DOM querying logic in
script.js
in a callback that is invoked upon the firing ofDOMContentLoaded
event:
window.addEventListener('DOMContentLoaded', () => {
const nextBtns = document.querySelectorAll(".btn-next");
console.log("nextBtns",nextBtns)
});
Source