Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to show only HTML elements that match the element selected by the drop-down list

How to show only HTML elements that match the element selected by the drop-down list ?

I want to show in my page only the element that matchup with the value that I choose in drop-down list

When I changed the value of select element to 3 i get the text Nodelist in the body of html

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const divs_exept_3 = document.querySelectorAll("body > div:not(.element3)")
const listOperations = document.querySelector('#elements');
listOperations.addEventListener('change', () => {
  if (listOperations.value === "3") {
    document.body.innerHTML = divs_exept_3;
  }
});
<div class="element1">
  <p>
    this is element 1
  </p>
</div>
<div class="element2">
  <p>
    this is element 2
  </p>
</div>
<div class="element3">
  <p>
    this is element 3
  </p>
</div>
<div class="element1">
  <p>
    this is element 1
  </p>
</div>
<div class="element2">
  <p>
    this is element 2
  </p>
</div>
<div class="element3">
  <p>
    this is element 3
  </p>
</div>
<select id="elements">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>

>Solution :

Here is a working script doing what I expect you want

const allDivs = document.querySelectorAll("body > div")
allDivs.forEach(div => div.hidden = true);
const listOperations = document.getElementById('elements');
listOperations.addEventListener('change', function() {
  const idx = this.value;
  allDivs.forEach(div => div.hidden = !div.classList.contains(`element${idx}`))
});
<div class="element1">
  <p>
    this is element 1
  </p>
</div>
<div class="element2">
  <p>
    this is element 2
  </p>
</div>
<div class="element3">
  <p>
    this is element 3
  </p>
</div>
<div class="element1">
  <p>
    this is element 1
  </p>
</div>
<div class="element2">
  <p>
    this is element 2
  </p>
</div>
<div class="element3">
  <p>
    this is element 3
  </p>
</div>
<select id="elements">
  <option value="">Please select</option>
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
</select>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading