Home > Net >  How to hide div if other divs not exists in Javascript
How to hide div if other divs not exists in Javascript

Time:07-10

I'm trying to hide the div title if related divs are no present:

Main HTML structure:

<div >
    <div id="title-1" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-11" >
        ... Content ...
    </article>
    <div id="title-2" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-21" > 
        ... Content ...
    </article>
    <article id="child-22" > 
        ... Content ...
    </article>
    <div id="title-3" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-31" > 
        ... Content ...
    </article>
    <article id="child-32" > 
        ... Content ...
    </article>
    <article id="child-33" > 
        ... Content ...
    </article>
    ...
</div>

Filtering the content I get:

<div >
    <div id="title-1" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
    <article id="child-11" >
        ... Content ...
    </article>
    <article id="child-12" > 
        ... Content ...
        </article>
    <div id="title-2" class='col-12 prov-title'>
        <h2>$category->name</h2>
    </div>
</div>

I mean, I need to hide the #title-2 div if #child-21 and #child-22 layers are not shown.

I understand that you would have to make a loop and look for .child pages by ID that start with the same number as the corresponding title div and hide it. I don't know much about the wildcards in the references to the id...

What would be the best way to do it in javascript?

Thnaks,

CodePudding user response:

Loop through the titles, and convert the title's ID to the prefix of the corresponding children. Then check if there are any elements with that kind of ID, and hide or show the title depending on it.

document.querySelectorAll(".prov-title").forEach(title => {
  let child_prefix = title.id.replace(/^title-/, 'child-');
  if (document.querySelector(`.child[id^="${child_prefix}"]`)) {
    title.style.display = 'block';
  } else {
    title.style.display = 'none';
  }
});
<div >
  <div id="title-1" class='col-12 prov-title'>
    <h2>Category 1</h2>
  </div>
  <article id="child-11" >
    ... Content 11 ...
  </article>
  <article id="child-12" >
    ... Content 12 ...
  </article>
  <div id="title-2" class='col-12 prov-title'>
    <h2>Category 2</h2>
  </div>
</div>

  • Related