Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I understand why the reading classlist part is null?

I’m trying to make a button in a website to hide/show my slides, and replace it with a different component. I did it before and it worked out, so I thought a similar code would work but it doesn’t.

Here is the html of my button:

<li><div class="behandlung-btn">Meine Behandlung</div></li>

And here is the html of the start of sliders:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<div class="sliders hideContent">
  <div class="slider home-slider clearfix" data-auto-play="8000">

Of course I closed the tag but since it’s pretty long I didn’t want to paste it all.

And here is the vanilla JS I tried:

   let showMoreBtn = document.querySelectorAll(".behandlung-btn");
  showMoreBtn.forEach((eachBtn) => {
    let textContainer = eachBtn.parentNode;
    let contentBox = textContainer.querySelector(".sliders").classList;
    eachBtn.addEventListener("click", (event) => {
      event.preventDefault();
      if (contentBox.contains("showContent")) {
        contentBox.remove("showContent");
        contentBox.add("hideContent");
        eachBtn.innerHTML = `<h12>ZEIG WENIGER</h12>`;
      } else {
        contentBox.add("showContent");
        contentBox.remove("hideContent");
        eachBtn.innerHTML = `<h12>ZEIG MEHR</h12>`;
      }
    });
  });

But it still says

Uncaught TypeError: Cannot read properties of null (reading 'classList')
at index.html:436:65
at NodeList.forEach (<anonymous>)
at index.html:434:19

I know there are a lot of questions in Stackoverflow about this typeError and I checked them out, but still couldn’t understand where the problem is, and also I’m a bit overwhelmed. Please help me out.

Thanks for the help in advance people!

>Solution :

It seems there is no element with .sliders class inside the textContainer element which is the parent of the button whose class behandlung-btn

You need to use document instead.

let contentBox = document.querySelector(".sliders").classList;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading