Creating an expandable table in JavaScript without relying on jQuery

I have a question that I can't seem to find the answer to. Despite numerous Google searches showing jquery solutions, I'd rather stick with vanilla JavaScript as I'm new to it and want to master it before moving on to libraries. My goal is to have a button collapse part of a table when clicked and then show those hidden parts again on a second click, essentially toggling the display of a specific element class.

When I click the button that calls the test() function, nothing seems to happen to my table. Here's the JavaScript code I'm using. I rely on collapse[0] because as far as I know, collapse is a nodeList and I always manipulate all elements together so checking the first one should be enough.

function test() {
    var collapse = document.getElementsByClassName("catOne");
    var i = 0; // Loop counter

    if (collapse[0].style.display === "table-row") {
        for (i = 0; i < collapse.length; i += 1) {
            collapse[i].style.display = "none";
        }
    }

    if (collapse[0].style.display === "none") {
        for (i = 0; i < collapse.length; i += 1) {
            collapse[i].style.display = "table-row";
        }
    }    
}

I've tested this function with the following code:

function test() {
    var collapse = document.getElementsByClassName("catOne");
    var i = 0; // Loop counter

    for (i = 0; i < collapse.length; i += 1) {
        collapse[i].style.display = "none";
    }

This works fine in collapsing the elements, meaning the issue likely lies within my if statement. However, my IDE, Netbeans, isn't flagging any errors, so it should be functioning correctly based on what I can see.

Thank you for any assistance provided.

Link to HTML and JavaScript: https://jsfiddle.net/ozjbekjy/

Answer №1

It seems like there may be a few issues that are causing some challenges for you.

Firstly, it is important to ensure that the test() function is defined earlier in the page than where it is being utilized. When using jQuery, this can be achieved by employing the $(function(){}) wrapper to assign event handlers once the DOM is ready. You can also implement a similar approach manually with guidance from this helpful answer.

If not, simply insert the <script> tag somewhere before the table (most likely within the <head> section) to enable the onclick functionality.

Additionally, instead of utilizing i += 1, consider using i++ as they both achieve the same outcome.

Furthermore, rather than directly manipulating the style attribute, utilize the classList.toggle() method to easily add and remove a class that includes the rule display: none, for instance:

CSS

.hide-me {
  display: none;
}

JavaScript

function test() {
  var collapse = document.getElementsByClassName("catOne");

  for (var i = 0; i < collapse.length; i++) {
    collapse[i].classList.toggle("hide-me");
  }
}

Your JSFiddle, incorporating the recommended enhancements: https://jsfiddle.net/ozjbekjy/4/

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

Are beta versions included in the "latest" versions of package.json?

Within the package.json file, you have the option to define a package to be synchronized with the most recent version: { ..., "devDependencies": { "gulp": "latest", ... }, ... } When "latest" is specified, does it encompass alpha ...

What is the method for generating a popover in HTML when a user hovers over a button?

In this scenario, I have implemented two status buttons with different colors. The green button corresponds to "RUNNING" and the red button indicates "TERMINATED", which are fetched from JASON data. Upon hovering over the green status button, the text "RU ...

Having trouble adding state values to an object

I have a specific state set up in my class: this.state = { inputValue: "", todos: [] } My issue lies within an arrow function where I am attempting to use setState to transfer the value of inputValue into todos. this.setState({ inputValue: & ...

Tips for closing an event when switching between tabs or windows

I'm in the process of developing an online test portal within my Angular application, and I need to figure out how to automatically close/end the session when a user navigates (opens a new tab or window) to a different page. Is there a way to achieve ...

The React date picker has limitations, as there are certain dates that users are unable

Recently, I came across an issue with a react date picker that I am using. Here is the code snippet: <DatePicker selected={selectedDate} onChange={handleDateChange} minDate={new Date()} className="form-control" /> In this image, when ...

Anchor no longer follows endpoint after Anchor ID is modified following creation - JSPlumb

I am currently developing an editor that involves placing shapes on a canvas and assigning IDs to them. When a shape is placed, endpoints are automatically created and attached to the shape using its ID as an anchor. //Function responsible for adding en ...

JavaScript - Loading image from local file on Linux machine

I have a server running and serving an HTML page, but I am trying to display an image from a local drive on a Linux machine. I've tried using file://.., but it doesn't seem to be working for me on Ubuntu 18.04. There are no errors, the img tag ju ...

There seems to be an issue with the JavaScript code failing after the AJAX request fails

When attempting to retrieve data from a local network IP address, everything functions correctly within the local network. However, issues arise when trying to access the data from outside the network. The problem is that the error block in jQuery does not ...

The display of 'App' seems to be experiencing issues within the render method

Can someone help me with this issue? I am encountering the following error: Uncaught Error: Invariant Violation: Element type is invalid - expected a string for built-in components or a class/function for composite components, but received an object. Bel ...

Delete auto-generated list using handlebars JS

I have successfully created a dynamic list using Handlebars.js and its template. However, I am now facing confusion on how to remove or delete items from the list using a function or specific code. As I am new to Handlebars, I would appreciate any help. ...

Combine identical items in a JavaScript array based on how often they appear

I have an array in JavaScript that looks like this: [ { quantity: 1, name: 'Menu sandwiches' }, { quantity: 1, name: 'Menu sandwiches' }, { quantity: 1, name: 'Menu sandwiches' }, { quantity: 1, name: 'Pizza' ...

Retrieve the highest value indexes from a three-dimensional array with JavaScript

In my dataset, I have an array structured like this: [34, 12, 56] [100,125,19] [30,50,69] The highest value in this array is 125, so the index [1,1] is returned. This means that 125, the highest value, can be found in row 1, column 1. To determine the i ...

The dialog box does not display properly on the screen when selecting multiple files

When I try to upload more than 25 files in the dialog box, the length of the box increases and there is no scrollbar to view all the files. Check out the screenshot: https://i.sstatic.net/vBcsh.png I added 36 files but couldn't see them all at once ...

Triggering AWS Lambda functions with SQS

Utilizing AWS and SES for sending emails and SMS through a Lambda function using NodeJs. I need to make more than 1k or 500 REST API calls, with the average call taking 3 seconds to execute a single lambda function request. It is essential to process mul ...

bootstrap 4 - logo in navbar brand stays the same even when scrolling

I integrated Bootstrap 4 and successfully created a navbar. However, I am encountering a conflict when trying to change the navbar logo upon scrolling down. Despite my efforts, it is not functioning as expected. Does anyone know how to resolve this issue? ...

Achieve the output of the .json data onto the HTML page utilizing JavaScript

Retrieve data from JSON file and display images in a gallery Successfully displaying the .json output on my HTML page. @Jesuraja - Would love to hear how you achieved this. I am currently facing the same issue with a JSON file containing image locatio ...

What is the best way to transform specific [x, y] coordinates into intervals of [xstart, xend, ystart, yend]?

In my project, I have the ability to draw tiles on an x-y grid and paint a provided png image. The objective is to then save these tiles as a .json file. Illustration of the issue: https://i.sstatic.net/XUfoS.png Currently, the JSON structure is created ...

What are the steps to leverage npm installed packages in my .js files?

I'm new to web development and I'm trying to incorporate node packages into my workflow. Specifically, I'm attempting to test out the axios ajax library. It seemed like this would be a simple task, but it's proving to be quite challeng ...

Error TS2451 in GatsbyJS: "react_1" block-scoped variable cannot be redeclared

Trying to implement typescript with custom routes in gatsbyjs: require("source-map-support").install(); require("ts-node").register(); exports.createPages = require("./src/createPages"); tsconfig.json { "include": ["./src/**/*"], "compilerOptions": ...

Resolving the "TypeError: Unable to access the 'then' property of undefined" issue in Node.js

I am currently working on connecting my app to a third party API using a node module. Below is the code I am utilizing for a school project. The library I am using to request data from the API can be found here. Note: This package is not being maintained ...