1

I've been looking around on some collapsables, most of them seem to use some extra code that doesn't seem to be needed or I can't understand haha. anyways, I made a super simple one and in my mind and logic it SHOULD work. but apparently it gets the error of

app.js:4 Uncaught TypeError: Cannot read property 'style' of null
    at btn (app.js:4)
    at HTMLButtonElement.onclick (index.html:9)

if someone would be so kind to properly explain to me WHY this isn't working so I might understand the logic better? here is snippet:

var content = document.querySelector(".content");
function btn(){
  if (content.style.display === "none") {
    content.style.display = "block";
  } else {
  content.style.display = "block";
  }
}
.content {
    display: none;
    overflow: hidden;
    color: red;
}
<button type="button" onClick="btn();">collapsible</button>
<div class="content">
  <p> inner content bla bla bla</p>
</div>

Thanks in advance! /Thuse

5
  • you dont have any element with ID of content Commented Oct 2, 2020 at 21:27
  • Change getElementById("content"); to querySelector(".content"); You use content class every where but are programming the javascript to look for the id. Commented Oct 2, 2020 at 21:28
  • You can use the native datails element for that: developer.mozilla.org/en-US/docs/Web/HTML/Element/details Commented Oct 2, 2020 at 21:30
  • thanks guys, long day of practice coding and was staring myself blind on stuff i should know. for taking ur time to help +rep Commented Oct 2, 2020 at 21:44
  • 1
    Your new code seems working except that you need to use none instead of block again in else condition. preferably move that querySeelector inside the function and not above the html codes as a global variable. @Thuse Commented Oct 2, 2020 at 21:45

1 Answer 1

2

As you have assigned a class name to that element so use querySelector instead of ID selector:

var content = document.querySelector(".content");

Please note that querySelectot returns the first occurance of a query. So if you have multiple elements you will need (querySelectorAll(".blah"))[x] to select the Xth element.

As a JQuery fan, using JQuery you just need 1 line of code:

function btn(){
    $(".content").toggle()
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.