Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

207
Views
How to setAttribute multiple elements in HTML using array?

I'm trying to hide multiple section in my HTML document based on button click, except for one. However, I got an error as follows:

Uncaught TypeError: arr[i].setAttribute is not a function

My code snippet look like below;

const hideOthers = (keepSec) => {
  let allSec = ["1Sec", "2Sec", "3Sec", "4Sec", "5Sec", "6Sec", "7Sec"];
  arr = allSec.filter((e) => e !== keepSec);
  console.log(arr);
  // arr.forEach(element => {
  //    element.setAttribute("hidden", true);
  // });
  for (var i = 0; i < arr.length; i++) {
    arr[i].setAttribute("hidden", true);
  }
};

Before, I tried using the long way and it works fine. It was by putting multiple lines of setAttribute like below:

1Sec.setAttribute("hidden", true);
2Sec.setAttribute("hidden", true);
3Sec.setAttribute("hidden", true);

How do I minimize the coding and perhaps run the function based on the data provided by the array? Any help is much appreciated

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

0

const Sec1 = document.querySelector('.Sec1');
const Sec2 = document.querySelector('.Sec2');

const hideOthers = (keepSec) =>{
    let allSec = [{name: 'Sec1', obj: Sec1 }, {name: 'Sec2', obj: Sec2}];
    
    arr = allSec.filter(e => e.name !== keepSec);
    for(var i = 0; i< arr.length; i++){
        arr[i].obj.setAttribute("hidden", true);
    }
}
hideOthers();

same other comment above, your array is a string[], not DOM object, so u can't setAttribute()
My solution is I use array object to store with: name for sort, obj for do setAttribute.

about 4 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 Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!