Adjusting the width of a div element using a button

I am currently diving into the world of JavaScript, React, and Node.js. My current challenge involves attempting to adjust the width of a div element using a button. However, I keep encountering the same frustrating error message stating "Cannot read property 'style' of null."

Let me share with you my JS code:

var sideNav = document.getElementById("side-nav");
var linksSideNavTop = document.getElementById("links-side-nav-top");
var linksSideNavBottom = document.getElementById("links-side-nav-bottom");

function openMenuTablet() {
    if (sideNav.style.width === '70px') {
        sideNav.style.width = '300px';
        linksSideNavTop.style.display = "block";
        linksSideNavBottom.style.display = "block";
    } else {
        sideNav.style.width = '70px';
        linksSideNavTop.style.display = "none";
        linksSideNavBottom.style.display = "none";
    };
}

And here is the corresponding CSS for styling:

#side-nav {
    position: fixed;
    background-color: #454545;
    height: 100%;
    width: 70px;
}

Answer №1

Check out this live demonstration:

function adjustSize() {
  document.getElementById('myElement').style.width = '500px'
}
#myElement {
  width: 250px; 
  height: 50px; 
  background: #aaa;
}
<div id="myElement"></div>
<button onclick="adjustSize()">Adjust size</button>

Answer №2

Indeed, the previous answers are accurate. I can also provide a demonstration using the .classList.toggle() method.

const box = document.querySelector(".box")
const button = document.querySelector("button")

button.addEventListener("click", () => {
  box.classList.toggle("toggle")
})
.box{
  width: 100px;
  height: 100px;
  background: red;
  margin-bottom: 10px;
  transition: 0.5s
}

.box.toggle{
  width: 200px;
}
<div class="box"></div>
<button>Toggle Class List</button>

If your class list includes toggle, the width of your div will increase. In JavaScript, the .toggle method both removes and adds the specified classList (in this case, "toggle").

Answer №3

Have you made sure to declare the elements with the identifiers links-side-nav-top, links-side-nav-bottom, and side-nav?

You may want to verify the existence of these ids by using console.log(linksSideNavTop);.

Answer №4

The error "Cannot read property 'style' of null" occurs when the code attempts to access the style property of an element that does not exist in the document (i.e., document.getElementById() is unable to find an element with the specified ID).

To resolve this issue, make sure there are no duplicate IDs with the same name and ensure that the document.getElementById() function is placed inside your function.

function openMenuTablet() {
    var sideNav = document.getElementById("side-nav");
    var linksSideNavTop = document.getElementById("links-side-nav-top");
    var linksSideNavBottom = document.getElementById("links-side-nav-bottom");

    if (sideNav.style.width === '70px') {
        // ...
    } else {
        // ...
    };
}

An alternative to document.getElementById() is document.querySelector():

document.querySelector("h1");         // Search html tag "h1"
document.querySelector(".rect");      // Search class name "rect"
document.querySelector("#square");    // Searcd id name "square"

To confirm if you have successfully retrieved the desired element, you can use console.log() to log the variable:

var sideNav = document.getElementById("side-nav");
console.log(sideNav);

// ...

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

Keep moving forward in Sailsjs even after sending back a response with res.json();

It will keep running even if the condition is met and the code inside return res.json() gets executed. _.each(rooms, function(room){ if(room.users.length == users.length) { return res.json(room); // <-- returns but execution continues } ...

Vue.js compatibility issue with SelectBoxIt jq plugin causing malfunction

On a page with numerous dynamically generated select boxes, I am looking to incorporate the jQuery selectBoxIt plugin from . Using Vue js, where is the best placement for the following code snippet to connect the plugin with the select elements? $('. ...

What is the process for including a new item in a JavaScript dictionary?

I'm currently learning JavaScript and I've encountered a challenge. I have a dictionary that I'd like to update whenever a button is clicked and the user enters some data in a prompt. However, for some reason, I am unable to successfully upd ...

Why Am I Still Getting a 431 (Request Header Fields Too Large) Error in My React App Despite Clearing

Whenever I try to run a post request in my React app, I encounter the "431 (Request Header Fields Too Large)" error and I'm unable to identify the cause. Is there anyone who can assist me with this problem? I've attempted various solutions based ...

Enhance your export capabilities with Material-UI theme integration for helper functions

Looking to create a new file that will house helper functions for multiple components sharing the same logic. The challenge arises when trying to access my locale.ts file within this new file in order to utilize the current language based on the theme (loc ...

Determine the absolute path with respect to a different reference path, rather than the current working directory

One of the challenges I'm facing with my Node.js module is how to easily allow developers to edit the location of the dependencies relative to the module file itself. The issue arises because the current working directory, accessed through `process.cw ...

Load information into a different entity

I need help with adding new values to an existing object. When I receive some form data from noteValue, I also have additional input data in my component under person that I would like to integrate into noteValue before saving it. let noteValue = form.va ...

Tips for implementing horizontal scroll in Material UI grid

I'm currently working on creating a kanban board using a grid layout with seven columns. Each column in the kanban board is built using Material UI grid components. Although I've attempted to implement the following CSS code, it doesn't see ...

Error message: "Angular.js encountered a typeError stating that V2.example is not a function"

Having recently started learning Angular.js, I came across a tutorial that was created about a year ago. In this tutorial, I am attempting to implement a search feature that takes user input and searches for it on Github.com. Below is the HTML code snippet ...

Find and make adjustments to the primary HTML document in your Magento online shop

Trying to enhance the top banner of my Magento website tamween.biz by adding a shadow effect PNG picture. Successfully managed this on my local server using firebug and creating a new class in the coding area with all selector properties modified in the bo ...

What is the best way to convert API data into a currency format?

Hello, I need assistance with formatting data retrieved from an API into a currency format. The code below successfully retrieves the data but lacks formatting. For instance, if the data displays as 100000000, I would like it to be formatted as IDR100.000. ...

When AJAX is invoked, the HTML content fails to display within a div

The following is the ajax script I am currently utilizing: mypage.php $(".sales_anchor").click(function(e) { e.preventDefault(); var store_username = $("#storeUsername").val(); var store_id = $("#storeID").val(); var sale_id = $(this).a ...

When I attempted to run `npm start`, an error with status code 1 was thrown,

Upon running npm start, the following error is displayed: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="2d4c5d5d6d1d031c031d">[email protected]</a> start /Users/user/Desktop/react-tutorial > react-script ...

Tips for removing the Y-Axis entirely from a CanavasJS chart

I'm working with a canvasJS chart and my goal is to completely hide the Y-Axis. I've managed to remove the Y-Axis line and title in this JSFiddle example. I came across these properties to hide the Y-Axis title and line, but I'm struggling t ...

Vue 3 Router view fails to capture child's event

After some testing, I discovered that the router-view component in Vue 3 does not capture events sent from its child components. An example of this scenario is as follows: <router-view @event-test="$emit('new-test-event')" /& ...

Is it possible to retrieve a constant value while developing a customized rule in typescript-eslint?

I am currently working on implementing a custom ESLint rule using @typescript-eslint/utils that will display a warning if the prop kind of Category does not match a specific Regex pattern: import { ESLintUtils, TSESTree } from '@typescript-eslint/util ...

Display the map using the fancybox feature

I have added fancybox to my view. When I try to open it, I want to display a map on it. Below is the div for fancybox: <div id="markers_map" style="display:none"> <div id="map_screen"> <div class="clear"></div> </div&g ...

Obtain a string in JSON format upon clicking in Angular 2

I am working on extracting the title from a json response using a click event. Currently, I can retrieve all the titles when the button is clicked, but I am looking for a way to obtain a specific title based on the button or a href that the user has clicke ...

The menu is failing to open the intended div index

Hello everyone, I’m currently facing an issue with a 2-dimensional dataset. The data has a nested structure that includes links. const data = [ // First Div Panel [ { id: 1, url: "/services", title: "Services" }, { ...

Bug in canvas rendering for Chrome versions 94 and 95

The Canvas drawing functionality in the Chrome browser seems to have some visible bugs. Here's an example of code that demonstrates this issue: const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d&apo ...