Issue
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:
<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;
Answered By - Mina
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.