Is there a way to conceal a div that holds a full table when the table consists of only one row?

I am relatively new to working with JS and HTML. I have attempted to use the following function, but unfortunately, I am not seeing any results. Any assistance would be greatly appreciated. Below is the JavaScript code as well as the HTML div and table where it should be implemented.

    function emptyTableRedisplay(table, uRowsMin)
    {
        if (! table || ! table.rows || table.rows.length >= uRowsMin)
            return;

        let styleHide = table.getAttribute("data-hide-style");
        if (! styleHide || styleHide === "")
            return;

        let idAlt = table.getAttribute("data-alt-id");
        if (! idAlt || idAlt === "")
            return;

        # find the enclosing div
        let el = table.parentNode;
        while (el && el.tagName.toLowerCase() == "div")
            el = el.parentNode;
        if (! el)
            return;

        var alt = el.parentNode.parentNode.getElementById(idAlt);
        if (! alt)
            return;

        el.classList.add(styleHide);
        alt.classList.remove(styleHide);
    }

This is what I included in the HTML:

<div id='emptyTableRedisplay'>                  
<h3>Header</h3>
<p>Notes</p>
<table class='data-table monetary' data-final-rows-to-not-sort='0' data-hide-style='1' data-alt-id='2'>
<tbody>
<tr>
<th class='sortable-col' data-collation-form='0-9'>Box #</th>
<th class='sortable-col'>Box Name</th>
<th class='sortable-col' data-collation-form='0-9'>Reported</th>
</tr>
</tbody>
</table>

Answer №1

To determine if the table row length is 1, you can check it and hide the div accordingly.

const emptyTableRedisplay = document.getElementById("emptyTableRedisplay");
const tableRows = document.querySelectorAll("#emptyTableRedisplay tr");
if (tableRows.length === 1) {
  // Uncomment the line below
  // emptyTableRedisplay.style.display = "none";

  //Just for demonstration
  emptyTableRedisplay.style.backgroundColor = "lightblue"
}
<div id="emptyTableRedisplay">
  <h3>Header</h3>
  <p>Notes</p>
  <table class="data-table monetary" data-final-rows-to-not-sort="0" data-hide-style="1" data-alt-id="2">
    <tbody>
      <tr>
        <th class="sortable-col" data-collation-form="0-9">Box #</th>
        <th class="sortable-col">Box Name</th>
        <th class="sortable-col" data-collation-form="0-9">Reported</th>
      </tr>

    </tbody>
  </table>
</div>

Answer №2

It seems like there might be a misunderstanding, but if the objective is to conceal the table in case of a single row, you can employ this onLoad function:

function hideTableIfSingleRow() {
    const table = document.getElementById('hideTableIfSingleRow');
    const rows = table.querySelectorAll('tr');
    if(rows.length == 1) {
        table.style.display = 'none';
    }
}

If you anticipate adding or removing rows post-loading, it would be necessary to utilize an event listener instead.

Answer №3

Another option is to achieve the same result using the following code:

const table = document.querySelector("#emptyTableRedisplay table");
if(table.rows.length === 1) {
  table.closest("div").style.display = "none";
}
<p>This content appears before the div</p>
<div id="emptyTableRedisplay">
  <h3>Header</h3>
  <p>Additional notes</p>
  <table class="data-table monetary" data-final-rows-to-not-sort="0" data-hide-style="1" data-alt-id="2">
    <tbody>
      <tr>
        <th class="sortable-col" data-collation-form="0-9">Box Number</th>
        <th class="sortable-col">Box Name</th>
        <th class="sortable-col" data-collation-form="0-9">Reported Information</th>
      </tr>

    </tbody>
  </table>
</div>
<p>This content appears after the div</p>

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

Is it possible to trigger the Facebook Pixel Code using the <noscript> element through programming?

Is there a way to programmatically call the Facebook Pixel Code using noscript? I am facing an issue with the Facebook Pixel Helper extension breaking when the script and noscript code are separated. Can a function be wrapped around the code or built in th ...

Downloading a file using JavaScript in a ReactJS application

When it comes to downloading a file from my server using a link like /api/ticket/1/download, I can simply copy and paste it into the browser and the download starts automatically with the correct filename extension. However, when trying to achieve the sam ...

Modify the button label as you input text into the textfield

I have a styled button along with an input field next to it. I want the button value to update dynamically as the user enters text in the input field. What is the easiest way to achieve this? This is my form: <form> <div class="span-3" id="b ...

Using C# within a JavaScript Element on a CSHTML webpage

Is there a way to integrate C# code into a JavaScript statement? Below is an example of the code I am trying to use: document.getElementById('part1').innerHTML = '' + '@Html.Partial("SelectCustomer.Views")' ' Views&apos ...

Creating animated effects through Javascript and CSS triggered by user events

As a beginner in javascript and CSS, I am experimenting with creating a simple animation that adjusts the transparency of an image when triggered by an event. However, I am facing an issue where the animation only works every other time the function is cal ...

It seems like encodeURIComponent is appending an extra character to my string

jQuery.ajax() is behaving strangely when escaping my data. For instance, if I make the following request: $.ajax({ url: 'somethingordinary', data: { name: 'Ihave¬aweirdcharacter'; } }); upon inspecting the XHR in ...

Effortless Sidebar Navigation for populating primary content

Initially, I must confess that even though this seems like a straightforward issue, I am just as puzzled as you are by my inability to solve it independently. With no prior experience in web development, I find myself in need of using GitHub Pages to docum ...

Retrieve JSON information from External document through Ajax

I'm trying to incorporate an external JS file that contains some sample JSON code. However, I'm encountering an error when I include the sample JSON code in the file, specifically at the ":". Interestingly, when I validate the code using online t ...

The container stays vacant as the bootstrap modal gracefully appears with a fading effect

I am trying to implement a basic bootstrap modal into my project, but I am encountering some issues with the code. When I click the "Launch demo" button, the modal fades in as expected, yet the container supposed to contain the ".modal-header", ".modal-bo ...

Issue with Editing the Layout of a Recently Created Page in Django CMS

I am brand new to the world of Django CMS and currently facing an issue that has me stuck. After adding a new module to an existing Django project and creating a new HTML page, I encountered a challenge with the templates configuration in settings.py. TEM ...

Viewing a PDF within a MUI tooltip

Currently, I am facing an issue where I am attempting to show a preview of a PDF file inside a Material-UI (MUI) Tooltip when a user hovers over a MUI ListItem. While I have successfully displayed previews of PNG and JPG files using Next.js' Image com ...

Having trouble applying styles to a component using forwardRef

I'm relatively new to React and still trying to wrap my head around the component's lifecycle. However, the issue at hand is proving to be quite perplexing. One thing that confuses me is why adding "setState(10);" causes the style of the "Test" ...

I am having issues with my Django application where I am unable to check

I have an HTML page where I want to only display the search bar if the table object passed in is not empty. However, my check doesn't seem to be working correctly. Here's my code: <!-- We'll show the search bar only if the user has acces ...

The deleteCell function will not properly function when directly targeting selected table rows (trs)

I'm currently facing an issue while trying to dynamically access a specific tr element. Although I believe that the tr is being selected, when attempting to use the deleteCell method, it gives an error stating that the object does not have such a meth ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...

What steps should I take to enable Google Maps style on mobile devices?

Hi there! I'm having some trouble styling my Google map. Sometimes the style loads correctly in browsers, and sometimes it doesn't. Another issue I've noticed is that when I view the page on mobile platforms like Android Chrome, iOS Safari, ...

Refreshing a Node.js server page upon receiving a JSON update

My web application serves as a monitoring interface for tracking changes in "objects" processed by the computer, specifically when they exceed a certain threshold. The Node Js server is running on the same machine and is responsible for displaying data in ...

What is the reason for requiring both a promise and a callback in order to store JSON data in a global variable?

In order to expose fetched JSON data to a global variable, it is necessary to use either a promise or a callback function. However, my current code is utilizing both methods... Currently, I am creating a promise using the .done function in jQuery. Within ...

Real-time database logging triggered by Firebase user authentication

exports.setupDefaultPullups = functions.auth.user() .onCreate( async (user) => { const dbRef= functions.database.ref; let vl= await (dbRef.once('value').then( (snapshot) => { return snapsh ...

What is the best way to convert a dynamic HTML table with input fields into an Excel spreadsheet?

I have developed a JavaScript function to convert an HTML table into an Excel sheet. However, I am facing an issue where some fields in the table are enclosed in input tags instead of td tags, causing them to not appear in the Excel sheet. function expo ...