Show or hide table columns easily without relying on jQuery

Within my HTML table that contains multiple columns, I aim to create a toggle feature for one specific column (in this case, the 4th column). Currently, I have accomplished this using jQuery:

document.write('<a class="toggle" href="#!" data-alt="Hide">Show</a>');
$(document).ready(function() {
    $('.toggle').click(function() {
        var el = $(this);
        var curr = el.text();
        el.text(el.attr("data-alt"));
        el.attr("data-alt", curr);
        $('td:nth-child(4),th:nth-child(4)').toggle();
    });
});

However, as this is the only part of my website that relies on jQuery, I would prefer to implement this functionality using pure Javascript. My attempts with getElementsByClassName and classList.toggle() weren't successful since I'm unable to add attributes to all td and th elements due to my Markdown-generated HTML structure.

I suspect that there might be a solution utilizing

document.querySelectorAll('td:nth-child(x)')
, but I haven't been able to crack it yet. Any suggestions?

Answer №1

A solution for your issue can be implemented in JavaScript using the

document.querySelectorAll('td:nth-child(x)')
statement.

To toggle the visibility of elements, you will need to create a separate function. Below is an example of how this function can be written:

var toggleVisibility = function (element) {
  element.style.display = (element.style.display === 'none')?'block':'none';
};

You can then use the following code snippet to toggle the visibility of a column:

document.querySelectorAll('td:nth-child(x),th:nth-child(x)').forEach(toggleVisibility);

Remember to replace 'x' with the specific column number you are targeting.

Answer №2

If anyone is looking for a different approach, I found a way to incorporate Vivek's solution (which can be found here) while also including original text swapping. Instead of using <a>, I opted for <input> + <label>:

var message = '<input id="checkbox" type="checkbox">\
    <label for="checkbox" id="clickme" onclick="toggle()"></label>.';

document.write(message);

var toggleDisplay = function (element) {
  element.style.display = (element.style.display === 'none')?'block':'none';
};

function toggle() {
    document.querySelectorAll('td:nth-child(4),th:nth-child(4)').forEach(toggleDisplay);
};

I then utilized CSS to insert the desired text:

#checkbox {
    display: none;
}

#checkbox:not(:checked) + #clickme:after {
    content: "Show";
}

#checkbox:checked + #clickme:after {
    content: "Hide";
}

There are numerous ways to achieve this task, but this method appeared to be the most direct for me. Thank you for the help!

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

"Troubleshooting: show() Function Not Functioning Properly

Though this may seem like a straightforward piece of code, I've hit a snag somewhere along the way. It's just evading my grasp. #div { display:none; } JS: function show() { var className = 1; $("#div." + className).show("slow") ...

sending data from Node.js to JavaScript

Attempting to utilize Google's provided sample code from their PhotoFrame repository has proven challenging. The framework consists of node.js, expressjs, jQuery, and more. I am struggling to pass a variable - let's refer to it as myString - from ...

Error encountered while adding x-ray-scraper to project using Npm

I am currently working on a Vue application and utilizing the x-ray-scraper library. However, when I attempt to run npm run serve in the terminal to preview the application locally, I encounter the following error: This dependency was not found: * _http_c ...

IE11 encounters an error labeled SCRIPT1010, signaling an expected Identifier when compiled

Lately, I've been encountering a strange issue in Vue.js. Here's the thing: my application runs smoothly on all browsers locally (yes, even IE 11). But when I compile it using npm run build and deploy it to my server (which essentially serves con ...

Guide to launching a web browser within a Phonegap app with a button click event

We are developing a PhoneGap application using HTML and JavaScript. Our goal is to integrate PayPal's website so that users can make payments with a simple button click event within the app, and then seamlessly return back to the application afterward ...

Resolving the issue of data transmission within Yii2's framework: Page-to-page data

I'm currently using Yii2-advanced-app and I have encountered an issue. I want to pass the selected value from a dropdown menu to a PHP code that displays a list with checkboxes on the same page. Here is an image for reference on what I am trying to ac ...

What is the process for retrieving data from a Cloudant document using Node.js?

I added the following code to the index.html page on bluemix: $(document).ready(function() { $("button").click(function() { var Cloudant = require('cloudant'); var password = "#password"; ...

Everything runs smoothly when initiating the API call through npm start, but unexpectedly crashes upon attempting to

Here is an API call located at http://localhost:9000/testAPI. Within the bin/www file: var port = normalizePort(process.env.PORT || '9000'); app.set('port', port); Inside the routes/index.js file: var express = require('express&a ...

What is the best way to iterate through an array and dynamically output the values?

I am facing an issue with a function that retrieves values from an array, and I wish to dynamically return these values. const AvailableUserRoles = [ { label: 'Administrator', value: 1 }, { label: 'Count', value: ...

Warning: The `children` attribute returned a value of NaN

I am currently working on a tic tac toe web application. I encountered an issue when clicking the "Ver Ranking" button, as it displays a warning message that I'm unsure how to address: Warning: Received NaN for the `children` attribute. If this is exp ...

Unable to load page callback using NodeJS Express and Passport-facebook

I'm facing an issue with my Node.js application using Express for authentication via Facebook as the URL /auth/facebook/callback is not loading. Here are the dependencies versions: Express: 4.13.3 Passport: 0.3.0 Passport-facebook: 2.0.0 Below is th ...

Tips on integrating googleapis with apps script

My goal: I am trying to implement the Google Calendar's API acl.list() in a Google Script using the UrlFetchApp.fetch() function. Issue: The Google script itself has an OAuth token when it runs. However, the problem arises when the UrlFetchApp.fetc ...

Error: Unable to process reduction on ships - function "reduce" is not functional

I created a boat visualization tool using a specific API. The API responds with a JSON that I then inject into a table. The issue: At times during the day, I observed the application would abruptly stop functioning and throw an error: Unhandled Rejection ...

Utilize vue-resource for updating information in the database

Within my Vue component, I have the following data setup: data() { return { revenueChart: '', limit: 12, labels: '', datasets: '' } }, In addition, there is a method that utilizes vue- ...

Ensuring the validity of float and non-empty values in JavaScript

Embarking on the journey of web development, I'm delving into basic applications. My current project involves creating a straightforward webpage to add two numbers and implementing preliminary validations - ensuring that the input fields are not left ...

Perform DOM manipulation prior to triggering the AJAX event to prevent CSRF Error

Currently, I am faced with a challenge while working on Django. My goal is to implement a chained AJAX call - meaning that once one call returns, it triggers additional AJAX calls. Despite thorough research and referencing the suggested methods in the Djan ...

What is the process for sending a message from the internet to a mobile device?

We are currently in the process of developing a website that sends SMS alerts to users for specific services, however I am struggling to set up a script that can perform this function. If anyone has any suggestions or recommendations for a solution, pleas ...

Browser extension for customizing the information on a webpage

I have a vision of developing a unique Chrome extension that has the ability to modify specific content on designated webpages. My aim is to transform something like the following: <td class="Data">Phone:</td> into something more interactive ...

Mastering the Rejection of Promises in Javascript with Graceful Elegance

One effective pattern using ES2017 async/await involves: async function () { try { var result = await some_promised_value() } catch (err) { console.log(`This block will be processed in a reject() callback with promise patterns, which is far mo ...

The ThreeJS WebGLRenderTarget is displaying an empty texture

Utilizing A-Frame and Three.JS, my goal is to render to a WebGLRenderTarget and generate a material based on its texture. Here's a snippet of the code: var targetPlane = new THREE.Mesh( new THREE.PlaneBufferGeometry(2, 2), new THREE.MeshBasicMate ...