Show/Hide divs with data-attribute based on checkboxex checked
Please add an else block to hide element when the checkbox is uncheck.
const elements = document.querySelectorAll(".letters");
const inputs = document.querySelectorAll("input");
inputs.forEach(item => {
item.addEventListener('change', function() {
if (this.checked) {
elements.forEach(e => {
if (e.getAttribute('data-text') == this.value) {
e.style.display = "block";
}
})
} else {
elements.forEach(e => {
if (e.getAttribute('data-text') == this.value) {
e.style.display = "none";
}
})
}
})
});
.letters {
display: none;
}
<div>
<div class="letters" data-text="b">B</div>
<div class="letters" data-text="b">B</div>
<div class="letters" data-text="b">B</div>
<div class="letters" data-text="a">A</div>
<div class="letters" data-text="b">B</div>
<div class="letters" data-text="c">C</div>
<div class="letters" data-text="a">A</div>
<div class="letters" data-text="c">C</div>
<div class="letters" data-text="a">A</div>
</div>
<input type="checkbox" value="a">a</br>
<input type="checkbox" value="b">b</br>
<input type="checkbox" value="c">c</br>