Home > other >  Hiding all instances of 2 divs depending on contents of a string
Hiding all instances of 2 divs depending on contents of a string

Time:05-11

I have a custom Wordpress blog post page that is showing personnel profile cards, 12 people at a time. Sometimes, people have a Twitter handle, others not. When the value entered in the backend for their handle is "none", both the title and the Twitter field should be hidden, for ALL people on the same screen (again, paginating through 12 people at a time). Otherwise, it should show both.

<p>Sample text</p>
<div >
  <p>Twitter Handle:</p>
</div>
<div >
  <p>@twitter</p>
</div>


<p>Sample text.</p>
<div >
  <p>Twitter Handle:</p>
</div>
<div >
   <p>None</p>
</div>

This is the javascript I was trying to use, but doesn't work:

let txt = document.getElementsByClassName("twitter-handle-text").innerText;
if (txt == "None") {
    document.getElementsByClassName('twitter-handle-title').style.display = "none";
    document.getElementsByClassName('twitter-handle-text').style.display = "none";
}

Any guidance would be appreciated!

CodePudding user response:

As mentioned, getElementsByClassName returns a HTMLCollection of all of the targeted elements.

To apply your intended logic to each profile card you will need to iterate over each one and run your checks and style updates on each iteration.

To make this easier, I'd suggest adding a wrapper to each card element in order to encapsulate your logic. Something like this:

<div >
  <p>Sample text.</p>
  <div >
    <p>Twitter Handle:</p>
  </div>
  <div >
    <p>None</p>
  </div>
</div>

Now you can select all of the card wrappers using a document interface such as getElementsByClassName or querySelectorAll.

const cards = document.querySelectorAll('.profile-card');

Once we have a collection of all of the profile-card elements, we can loop over each wrapping element using the forEach array method. Now that we are encapsulated within each card we can apply your logic.

For the inner selectors I'd recommend using querySelector as we only need to select a single element by class name rather than a collection.

cards.forEach((card) => {
  if (card.querySelector('.twitter-handle-text').innerText === 'None') {
    card.querySelector('.twitter-handle-title').style.display = 'none';
    card.querySelector('.twitter-handle-text').style.display = 'none';
  }
})

Hope this helps!

  • Related