Inquiries about creating collapsible content using html, css, and javascript

I have been exploring collapsibles and noticed that many of them use extra code that seems unnecessary or confusing. I decided to create a simple one based on my logic, but it's throwing an error:

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

If someone could kindly explain why this isn't working, it would help me understand the logic better. Here is the 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

Answer №1

Since a class name has been assigned to the element, it is recommended to use querySelector instead of an ID selector:

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

Keep in mind that querySelector only returns the first instance of a query. If there are multiple elements, you will need to use (querySelectorAll(".blah"))[x] to select the Xth element.

For those who prefer JQuery, achieving the same functionality only requires 1 line of code:

function toggleContent(){
    $(".content").toggle()
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for automating the activation of intents at specific scheduled times in Dialogflow

I'm attempting to automatically trigger intents in Dialogflow to obtain the user's contact details at a scheduled time. Is it possible to achieve this using JavaScript? If so, could you please provide the code? ...

Get the data from the files in the request using request.files in Node.js

Is there a way to read the content of a file (either a txt or CSV file) that a user uploads without saving it to local storage? I know I can save the file in an upload directory and then read it from storage. However, I'm wondering if there is a way ...

Designing hover-activated submenus and ensuring they appear at the forefront

I am currently utilizing jquery to implement a dropdown submenu on hover action. Here is the structure of the code: <div id="menucontainer"> <ul id = "topmenu"> <li><a onmouseover="javascript:show('div_1');">menu_1 ...

`replace an element and its children with the same identifier`

For my project, I am attempting to dynamically load e-book chapter pages using ajax requests. Here is an example of the HTML markup I am working with: <html><body> <div id="p5"> <div id="p6"> <p class="heading">heading1</p ...

Ensure consistency of wrapper height across various browsers

Ensuring consistent height for a wrapper across all browsers is proving to be a challenge. Methods such as using min-height and setting height to 100% have been attempted, but unfortunately, results are not as intended. So how can this issue be resolved? ...

How can we send state updates directly to a conditionally rendered React component?

I am currently developing a React application with a tab section that displays specific components upon clicking on a tab. Initially, I have my parent component: class Interface extends Component { constructor(props) { super(props); ...

An issue arose with ReactDom during the development of the application

I am currently working on my final assignment for the semester, where I have created a project and finished coding it. However, when I try to load the localhost, the page remains blank even though the console in vsc shows no errors. Upon checking the conso ...

Ways to display an error notification alongside another message

I have set up a validation directive that requires users to check a box. If the checkbox is left unchecked, an error message will be displayed. However, I am facing an issue where the message overlaps with the checkbox text. https://i.sstatic.net/iTKoo.jp ...

Utilizing the submission function in javascript

As a newcomer to javascript, I am encountering some challenges when trying to implement form submit action onclick using javascript. The issue arises when I attempt to incorporate all the validation checks using if-else conditions. At that point, the fu ...

Manipulate JavaScript programmatically using Python and Selenium

Is it possible to programatically set up a Javascript override on a webpage using Selenium (either Geckodriver or Chromedriver) and Python? I have the modified JavaScript saved on my local computer. The procedure outlined in this Stack Overflow article w ...

AngularJS: Solving the issue of controllers not exchanging data by utilizing a service

I am working with the following controllers and service: angular.module('myApp', []); angular.module('myApp').factory('ShareService', function() { var information = {}; information.data = ""; information.setD ...

What is the best way to pass a file and a string to my C# backend using JQuery Ajax?

I have a user interface with two input fields - one for uploading a file and another for entering the file's name. I need to capture both the file (as binary data) and its corresponding name in a single AJAX request, so that I can upload the file usi ...

The CSS on my website is causing issues with the recaptcha functionality

Recently, I've been working on a website that requires spam protection for the contact form. To combat this issue, I decided to integrate reCAPTCHA into the form. However, after completing the form and applying the necessary CSS styles, I noticed tha ...

Iterate over a collection of HTML elements to assign a specific class to one element and a different class to the remaining elements

Forgive me if this is a silly question, but I have a function named selectFace(face); The idea is that when an item is clicked, it should add one class to that item and another class to all the other items. This is what I currently have: HTML <div c ...

Troubleshooting problem with hiding options in Jquery Chosen

Utilizing the chosen multiple selection feature, I have encountered an issue where selected options remain visible after being hidden and updated. Here is the code snippet: $("#ddlcodes").find("option[value ='" + codeValue + "']").hide(); $("#d ...

The Angular routing functionality appears to be malfunctioning

I am currently implementing routing in my project using basic angular route with Angular 1.3.0. Here is the content of my app.js file: 'use strict'; var routerApp = angular.module('mcw', [ 'ngRoute', 'mcw.controll ...

Creating tiles that can be easily stacked to the side

Seeking a solution to a unique layout challenge, I am hoping for some guidance. After searching and not finding exactly what I need, I turned to this platform for help. I want to create a view where multiple boxes (divs) are contained within the same paren ...

CSS - What's the source of this mysterious whitespace?

I'm currently making adjustments to a Wordpress website that is designed to be responsive. The site uses media queries to adapt its display based on the user's screen size, and everything looks great except for when the screen width is at its sma ...

Troubleshoot: Bootbox Confirm Functionality Issues

Can anyone help me troubleshoot this issue? I'm trying to implement code that uses bootbox.confirm when deleting a file, but it's not functioning correctly. $('#fileupload').fileupload({ destroy: function (e, data) { var that = $(th ...

Guide on saving the token in local storage or cookies to grant access to specific web pages for users

Currently, I am in the process of developing an authentication system using Node.js, MySQL, and Express. Initially, I focused on saving and verifying user credentials in the database. Recently, I incorporated JWT (JSON Web Token) into the system. My next s ...