Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

106
Visualizações
Hide and display DIV's depending on matching class and content

I am trying to hide or display a div depending on whether it has a matching class with the content.

In this example the class called 'Countries' contains the text 'USA'. I would like to display the 'search-result' div if has 'USA' in the class called 'Country'.

Here is my attempt. It hides the div 'Country' if I remove this

document.querySelectorAll(".search-result").forEach((z) => {

and change ? (z.style.display = "block") : (z.style.display = "none");

to y.style.display

but I need to hide the overall div.

Can anyone help please?

<html>
  <head>
    <style></style>
    <script src="https://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
  </head>
  <body>
    <div class="Countries">USA</div>

    <div class="search-result">
      <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
      <div>The body of the result</div>
    </div>
    <div class="search-result">
      <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
      <div>The body of the result</div>
    </div>
    <div class="search-result">
      <div class="Country d-none">Canada, Bolivia, Paraguay</div>
      <div>The body of the result - you should not see this one</div>
    </div>
    <div class="search-result">
      <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
      <div>The body of the result</div>
    </div>
    <div class="search-result">
      <div class="Country d-none">Canada, Bolivia, Paraguay</div>
      <div>The body of the result - you should not see this one</div>
    </div>

    <script type="text/javascript">
      document.querySelectorAll(".Countries").forEach((x) => {
        document.querySelectorAll(".Country").forEach((y) => {
          document.querySelectorAll(".search-result").forEach((z) => {
            y.innerText.includes(x.innerText)
              ? (z.style.display = "block")
              : (z.style.display = "none");
          });
        });
      });
    </script>
  </body>
</html>
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Since you already use the className d-none don't use z.style.display = "none|block"
Use instead z.classList.toggle("d-none", !isMatch) where isMatch is a boolean value given the text was found. Use String.prototype.includes() for that matter.

More info: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

Example:

// UTILITY functions

const EL = (sel, PAR) => (PAR||document).querySelector(sel); 
const ELS = (sel, PAR) => (PAR||document).querySelectorAll(sel); 
const trimLCase = (str) => str.trim().toLowerCase(); 

// APP

const EL_search = EL("#search");
const filterResults = () => {

  // Get the search value
  const search = trimLCase(EL_search.value);
  
  // Filter search results!
  ELS(".search-result").forEach(EL_result => {
    const EL_country = EL(".Country", EL_result);
    const content = trimLCase(EL_country.textContent);
    const isMatch = content.includes(search);
    EL_result.classList.toggle("d-none", !isMatch);
  });
};


// INIT, EVENTS

EL_search.addEventListener("input", filterResults);
filterResults();
/* Utility classes */

.d-none {
  display: none;
}
Search: <input id="search" value="USA" type=search autocomplete=off>

<div class="search-result">
  <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
  <div>1. The body of the result U,C,B,P</div>
</div>
<div class="search-result">
  <div class="Country d-none">USA, Canada, Paraguay</div>
  <div>2. The body of the result U,C,P</div>
</div>
<div class="search-result">
  <div class="Country d-none">Canada, Bolivia, Paraguay, Guatemala</div>
  <div>3. The body of the result C,B,P,G</div>
</div>
<div class="search-result">
  <div class="Country d-none">USA, Paraguay, Guatemala</div>
  <div>4. The body of the result U,P,G</div>
</div>
<div class="search-result">
  <div class="Country d-none">Bolivia, Paraguay</div>
  <div>5. The body of the result B,P</div>
</div>

Above, since I used an <input> for demo, instead of

const search = EL_search.value.trim().toLowerCase();

for your specific case you might want to use:

const search = EL(".Country").textContent.trim().toLowerCase();

but it makes no sense to go for some Class Elements like .Country since it could later during development lead to false positives.

about 4 years ago · Juan Pablo Isaza Relatório

0

    <html>
      <head>
        <style></style>
        <script src="https://stacksnippets.net/scripts/snippet-javascript-console.min.js?v=1"></script>
      </head>
      <body>
        <div class="Countries">USA</div>
    
        <div class="search-result">
          <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
          <div>The body of the result</div>
        </div>
        <div class="search-result">
          <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
          <div>The body of the result</div>
        </div>
        <div class="search-result">
          <div class="Country d-none">Canada, Bolivia, Paraguay</div>
          <div>The body of the result - you should not see this one</div>
        </div>
        <div class="search-result">
          <div class="Country d-none">USA, Canada, Bolivia, Paraguay</div>
          <div>The body of the result</div>
        </div>
        <div class="search-result">
          <div class="Country d-none">Canada, Bolivia, Paraguay</div>
          <div>The body of the result - you should not see this one</div>
        </div>
    
        <script type="text/javascript">

const countries = document.querySelector(".Countries");

const searchResults = document.querySelectorAll(".search-result");

for(let i = 0; i < searchResults.length; i++) {
    if(countries.innerText !== searchResults[i].innerText) {
        searchResults[i].parentNode.style.display = "none"
    } else {
        searchResults[i].parentNode.style.display = "block"
    }
}

    </script>
  </body>
</html>
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda