Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

202
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda