Home > Back-end >  Hide span if ID variable is 0
Hide span if ID variable is 0

Time:08-27

I've tried numerous solutions to this that I've found here and none work. Either I don't know what I'm doing or my situation is unique.

I have span IDs that count the number of specific div classes on a page. For example:

var numNew = $('.new').length;
document.getElementById('numNewOutput').innerHTML = numNew;

which counts the number of divs with the class "new" corresponds to

<tr style="color:var(--new);"><td><span  id="numNewOutput"></span></td><td >NEW</td></tr>

Which puts that value into the span.

This works perfectly, BUT if the value is 0, I want it to be hidden. There a multiple spans with the same class and unique IDs that pull different div counts. A working page is here (the tallys I am addressing appear when you click "Shit I've watched & read" at the top): http://rubbersquare.com/watched2023/

Some (not all) of the other variables are

var numNewfilm = $('.newfilm').length;
    document.getElementById('numNewfilmOutput').innerHTML = numNewfilm;
    var numNewnonfictionfilm = $('.newnonfictionfilm').length;
    document.getElementById('numNewnonfictionfilmOutput').innerHTML = numNewnonfictionfilm;
    var numNewepisode = $('.newepisode').length;
    document.getElementById('numNewepisodeOutput').innerHTML = numNewepisode;
    var numNewnonfictionepisode = $('.newnonfictionepisode').length;
    document.getElementById('numNewnonfictionepisodeOutput').innerHTML = numNewnonfictionepisode;
    var numNewshort = $('.newshort').length;
    document.getElementById('numNewshortOutput').innerHTML = numNewshort;

with HTML:

<tr style="color:var(--new);"><td><span  id="numNewOutput"></span></td><td >NEW</td></tr>
<tr style="color:var(--new);"><td><span  id="numNewfilmOutput"></span></td><td >films</td></tr>
<tr style="color:var(--new;)"><td><span  id="numNewnonfictionfilmOutput"></span></td><td >nonfiction films</td></tr>
<tr style="color:var(--new;)"><td><span  id="numNewepisodeOutput"></span></td><td >episodes</td></tr>  
<tr style="color:var(--new;)"><td><span  id="numNewnonfictionepisodeOutput"></span></td><td >nonfiction episodes</td></tr>  
<tr style="color:var(--new;)"><td><span  id="numNewshortOutput"></span></td><td >shorts</td></tr>

CodePudding user response:

Example how it could be done:

const numNew = document.querySelectorAll('.new').length;
const output = document.querySelector('#numNewOutput');
if (numNew) {
  output.textContent = numNew;
} else {
  output.hidden = true;
}

P.S. Please don't mix jquery selectors with vanilla js selectors.

And never use var

  • Related