0

please tell me how to do in this function so that the value having 0 is not displayed

const elements = document.querySelectorAll('.age-count')

elements.forEach(function(el) {
  const count = el.textContent
  const title = declination(count, [' год', ' года', ' лет'])
  const age = count + title

  el.textContent = age
})

function declination(number, titles) {
  cases = [2, 0, 1, 1, 1, 2];
  return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
}
<div class="age-count">22</div>
<div class="age-count">0</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

1

To hide the element check that it's text is equal to 0, and if so set it to display: none.

const elements = document.querySelectorAll('.age-count')

elements.forEach(function(el) {
  const count = el.textContent
  
  if (+count === 0)
    el.style.display = 'none';
    
  const title = declination(count, [' год', ' года', ' лет'])
  const age = count + title

  el.textContent = age
})

function declination(number, titles) {
  cases = [2, 0, 1, 1, 1, 2];
  return titles[(number % 100 > 4 && number % 100 < 20) ? 2 : cases[(number % 10 < 5) ? number % 10 : 5]];
}
<div class="age-count">22</div>
<div class="age-count">0</div>

Note that this still follows the logic to update the text within the element, even though it has been hidden. You can easily amend the logic flow to avoid that, though.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Is the `+` before the count to transform it into a number? – ChenBr Oct 22 '22 at 13:24
  • 1
    @ChenBr yes, that's right. It's a shorthand way of coercing a string to a Number - more info [here](https://stackoverflow.com/q/6682997/519413). It would be possible to compare the values as text, but that's rather brittle as it would be broken by any whitespace at the end of the textContent in the HTML. – Rory McCrossan Oct 22 '22 at 13:25
  • I see. Thanks for the information! Appreciate it. – ChenBr Oct 22 '22 at 13:31