Home > OS >  Hide a firstElementChild if parentElement doesn't contain text
Hide a firstElementChild if parentElement doesn't contain text

Time:09-07

I need to hide an icon if there's no text in the parentElement (h4.undefined). Sometimes text can be present but in the situation it is not, I need to hide the icon.

The way I did it, gives me an error in console.log of browser.

What would be a proper way to do it?

<div >
  <h4 >
    <i  aria-hidden="true">i</i>
    <!-- some text might be possible here but sometimes it's not -->
    <!-- if here is no text, hide the icon -->
  </h4>
  <h4 >
    undefined
  </h4>
</div>

JS code:

let test = document.querySelectorAll('h4.undefined');

Array.from(test).forEach(i => {
  if(i.textContent.includes('undefined')) {
      i.style.display = 'none'; // hiding el that contains undefined text
      // let inner = document.querySelectorAll('.icon-calendar');
      // Array.from(inner).forEach(j =>{
      //     j.style.display = 'none';
      // })
  }
  if(i.childNodes.length === 0) {

  } else {
    i.childNodes[1].style.display = 'none'; // error in browser's console.log - Cannot read properties of undefined (reading 'style')
  }
});

CodePudding user response:

Its because the second h4 tag with text content undefined does not contains any childNodes.

I hope this is what you are looking for. If yes then you have to use else if ins the second condition check

let test = document.querySelectorAll("h4.undefined");

Array.from(test).forEach((i) => {
  if (i.textContent.includes("undefined")) {
    i.style.display = "none"; // hiding el that contains undefined text
    // let inner = document.querySelectorAll('.icon-calendar');
    // Array.from(inner).forEach(j =>{
    //     j.style.display = 'none';
    // })
  }
  // Change here
  else if (i.childNodes.length === 0) {
  } else {
    i.childNodes[1].style.display = "none";
  }
});
<div >
  <h4 >
    <i  aria-hidden="true">i</i>
    <!-- some text might be possible here but sometimes it's not -->
    <!-- if here is no text, hide the icon -->
  </h4>
  <h4 >undefined</h4>
</div>

  • Related