Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

203
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda