Modifying the CSS design of specific columns within a table created using JavaScript

A unique way to showcase JSON data in a table is by utilizing a for loop within a function. This method, however, does not assign an ID or Class to the table.

To hide the final three columns of this table using CSS, the following code can be employed (where (n) signifies the column number):

#divIdName table tr td:nth-child(n) { 
display: none; }

#divIdName table th:nth-child(n) { 
display: none; }

In an attempt to reveal these hidden columns through JavaScript functions with queryselector, I encountered an issue where only one column was successfully displayed. The content of this lone visible column comprised concatenated headings and first row data from each of the three columns.

If you have insight on how to resolve this problem and ensure all columns are shown correctly, please share your expertise.

UPDATE: I neglected to mention that the showColumnN function includes a condition to verify the presence of a specific string within an array before proceeding with the column revelation process.

Answer №1

Only one of the hidden columns is currently being displayed

This is due to selecting only the first td and th that match those selectors, when there are likely multiple tds that match (one per row).

If you choose to continue down this path (which I advise against), you would need to iterate through them like so:

function showColumnN(n) {
    showAll(document.querySelectorAll("td:nth-child(" + n + ")"));
    showAll(document.querySelectorAll("th:nth-child(" + n + ")"));
}
function showAll(list) {
    Array.prototype.forEach.call(list, function(element) {
        element.style.display = "block";
    });
}

However, it may be more efficient to use a CSS approach where you can assign classes to the table for displaying specific columns:

table.show1 tr > th:nth-child(1), table.show1 tr > td:nth-child(1) {
    display: block;
}
table.show2 tr > th:nth-child(2), table.show2 tr > td:nth-child(2) {
    display: block;
}

...and so forth. Therefore, to display column 2, you would do:

document.querySelector("selector-for-the-table").classList.add("show2");

(Alternatively, consider using hideX classes to hide columns and dynamically adding/removing them as needed, avoiding the need to set the display property to block.)


On a side note: The default display value for td and th elements is not block, but rather table-cell.

Answer №2

If you want to achieve the same result with less code, consider T. J. Crowders' more concise solution:

const table = document.getElementById("divIdName");
const rows = table.getElementsByTagName("tr");
rows.forEach((row) => {
  const elems = row.getElementsByTagName("td");
  for (let i = 0; i < 4; i++) {
    elems[elems.length - 4 + i].style.display = "block";
  }
});

T. J. Crowders has provided a shorter alternative to accomplish this task.

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

The issue of the useRef object returning undefined in React/React-Native is causing confusion during

Every time I attempt to access the ref object, I keep receiving an error stating that it is 'undefined'. My goal is to map through an array of images and use useRef to access each individual one. To start off, I initialized the useRef like this: ...

Is it possible for two Bootstrap icon class names to be used sequentially with one taking precedence over the other?

I am having an issue with toggling a class name in my code. I have a class named (bi bi-clipboard) and I want to change it to (bi-clipboard-check) when it is clicked. However, the problem is that the new class name gets added next to the existing one like ...

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

End: unrelated, lacking responses

I have a question I'd like to discuss: Whenever I utilize the following code snippet: async function createNewElement(req,res){ const start1 = new Date().getTime(); console.log("start time 1 ", start1) await new Promise((resolve) => setT ...

Expanding form fields dynamically with AngularJS

I am currently working on a form that allows users to click a '+' sign in order to add new lines. I've set up a function to be called when the button is clicked, which should push a new line into the array. However, for some reason the new l ...

Tips on incorporating "get_template_directory_uri" into a JavaScript function

I am currently working on my WordPress PHP file code, where I have included a JavaScript snippet to display names and images from a query. While the names are being displayed correctly, I am encountering an issue with the images not showing up. After tryi ...

Using Python with Selenium and JavaScript for Logging in

When using Selenium and Python, I am attempting to log in to a website but encountering difficulties. The issue is that the source code does not display the necessary Id=apple_Id required for sending login information, although it can be seen when inspecti ...

Issue with Typescript and react-create-app integration using Express

I'm relatively new to Typescript and I decided to kickstart a project using create-react-app. However, I encountered an issue while trying to connect my project to a server using express. After creating a folder named src/server/server.ts, React auto ...

Tips for creating a responsive floating page div

Hey there, I'm still fairly new to web development and have a question regarding a registration page that is displayed as a floating div above the main page. How can I ensure that this div is centered in a responsive way? The pages are separated and ...

"Enhance your online shopping experience with a React.js popup modal for

In the midst of developing a shopping cart, I find myself facing a challenge in making the modal pop up when clicking on the shopping cart icon. The semantic-ui documentation for modals has not provided clear instructions on achieving this functionality, s ...

Troubleshooting a glitch with passing a variable to a PHP script using AJAX

Explanation of the page functionality: When the quiz php page loads, a user can create a score using a function in quiz.js. This score is then stored in a variable score within quiz.js Once the score is generated, the user must click a button to move on ...

What is the reason behind one function triggering a re-render of a component while the other does not in Next.js?

I am currently working on a Next.js web application where one of the pages contains two functions that utilize useState() to add or remove emails from an array. const [invites, setInvites] = useState([]) // other code const lmao = () => { console.lo ...

Identifying whether a Alphabet or a Digit has been Pressed - JavaScript

I understand that it is possible to detect if a key has been pressed and identify which key was pressed using JavaScript. In order to check if a key is down or pressed, jQuery can be utilized with ease: $( "#some id" ).keydown(function() or $( "#m" ). ...

How can I implement horizontal scrolling on a material-ui table containing numerous columns?

As I work with the React Material-UI framework, I am using this table example as a guide. However, I am facing an issue where my table becomes overcrowded when I have numerous columns, causing the content to be cut off. I recently came across the material ...

Listening to events on the iterative variable of NgFor directive in Angular 2

Angular2 has been my latest exploration in solving a unique data binding challenge. In my UI, I've presented a javascript array of objects like a database recordset in an HTML table. Each row contains menus and inputs allowing users to modify the rec ...

What is the process for editing a JSON file and preserving the modifications?

I have a JSON file with a key (food_image) and I am looking to dynamically assign the index value in a loop to it, such as food_image0, food_image1 ... food_image{loop index}. After that, I aim to save this modified JSON file under a new name. All values ...

What is the best way to showcase a container within a two-column layout?

Looking to showcase the content of two columns exclusively within a container, with each column spaning the full width of the page, just like the image below. Can this be achieved using css grid? Your assistance and support is greatly appreciated. < ...

The entire image is unable to be shown within the div

When adding images to a carousel, I encountered an issue where only the top half of the image is displayed on the page. It seems that the image is not adjusting itself to fit the div container properly, resulting in only a portion of it being visible behin ...

The Vue v-bind:class feature does not always update immediately when the value of the binded object is changed

When utilizing Vue, it seems that developers often use v-bind:class to add dynamic classes to elements. However, in the example below, this method appears to not function as expected. //Html <div id="mainapp"> <span class="star" v-bind:class="{ ...

Placing additional text beside a nicely aligned box

I am struggling to figure out how to position text in the center left of a box that is located in the top right corner of my HTML template. <table class="label"> <tr> <td class="sign">F</td> ...