Home > OS >  Simplify code by applying property to multiple variables at once
Simplify code by applying property to multiple variables at once

Time:10-11

I want to simplify this code

let a = document.querySelector(".arrow");
    b = document.querySelector(".demo-desc1");
    c = document.querySelector(".demo-title h3");

    a.style.display = "none";
    b.style.display = "none";
    c.style.display = "none";

so I don't have to write style.display = "none" for every variable but rather to apply the propery for all variables at once.

Thank you.

CodePudding user response:

If there's only one element of each in the DOM, put them all into a selector string, then iterate over the matching elements.

for (const elm of document.querySelectorAll('.arrow, .demo-desc1, .demo-title h3')) {
  elm.style.display = 'none';
}

If there are multiple such elements, then you'll need

const selectors = ['.arrow', '.demo-desc1', '.demo-title h3'];
for (const s of selectors) {
  document.querySelector(s).style.display = 'none';
}

But, in this sort of situation, an even better approach would be to toggle a class of a parent container, and have CSS rules that hide those elements when the class is on the parent container. I don't know what the rest of your HTML is like, but perhaps something like

<div class="demo-container">
  <more HTML here>
</div>
.hide-children .arrow, .hide-children .demo-desc1, .hide-children .demo-title h3 {
  display: none;
}

Then all you need is

document.querySelector('.demo-container').classList.add('hide-children');
  • Related