questions

Why do I get uncaught error on my script?

Rate this post

SO, I have been trying to implement a custom jQuery element on my WordPress and so far so good. I was able to enqueue the scripts and stylesheets and get them embedded in my pages. However, I get an uncaught error for my script. Here is the script.

var coll = document.getElementsByClassName("collapsiblecustom");
var i;
jQuery(document).ready(function($){
  jQuery("#collapsiblecustom").click(function($){
    for (i = 0; i < coll.length; i++){


this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
  content.style.display = "none";
} else {
  content.style.display = "block";
}
}
});
});

And here is the error that I get when I click on the element.

Uncaught TypeError: Cannot read property ‘style’ of null

Please note that the error comes from the first line of the if function.

 

✔️Solution:

You must validate that the element exists:

var content = this.nextElementSibling;
if (content) {
    if (content.style.display === "block")
        content.style.display = "none";
    } else {
        content.style.display = "block";
    }
}

Leave a Reply

Your email address will not be published.

Back to top button