I am trying to add the code on this page: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements
but it give me an error on the js:
Uncaught TypeError: Cannot read properties of null (reading 'getElementsByClassName') at main.js?ver=5.8.2:35
I am trying to add it on: https://nuovosito.lealternative.net/test-browser-4/
It seems to work fine, except that it can't find an active class to the current button.
EDIT:
here the part of code that give error:
// Add active class to the current button (highlight it)
var btnContainer = document.getElementById("myBtnContainer");
var btns = btnContainer.getElementsByClassName("bottone");
for (var i = 0; i < btns.length; i ) {
btns[i].addEventListener("click", function(){
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace(" active", "");
this.className = " active";
});
}
CodePudding user response:
Your problem is that the script is executing before #myBtnContainer
has loaded onto the page. This can be fixed by placing your <script>
tag for main.js
in your <body>
below all of the other HTML content, or adding the defer
tag like so:
<script src='https://nuovosito.lealternative.net/wp-content/themes/twentytwentyone/assets/js/main.js?ver=5.8.2' id='js-file-js' defer></script>
Another way to fix it would be to wrap all of your scripts in a DOMContentLoaded
listener, which will make the things inside only execute after all HTML elements are loaded.
document.addEventListener('DOMContentLoaded', () => {
// put your whole script here
});