• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

116
Views
Simplify code by applying property to multiple variables at once

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.

about 3 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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');
about 3 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error