Search code examples
javascriptmatchhtml-selectnodelist

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

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>