Estoy tratando de ocultar varias secciones en mi documento HTML en función del clic del botón, excepto una. Sin embargo, recibí un error de la siguiente manera:
Uncaught TypeError: arr[i].setAttribute is not a functionMi fragmento de código se ve a continuación;
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); } };Antes, probé usando el camino largo y funciona bien. Fue poniendo varias líneas de setAttribute como a continuación:
1Sec.setAttribute("hidden", true); 2Sec.setAttribute("hidden", true); 3Sec.setAttribute("hidden", true);¿Cómo minimizo la codificación y quizás ejecuto la función en función de los datos proporcionados por la matriz? Cualquier ayuda es muy apreciada
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(); El mismo otro comentario anterior, su matriz es una cadena [], no un objeto DOM, por lo que no puede establecer el Atributo ()
Mi solución es que uso un objeto de matriz para almacenar con: nombre para ordenar, obj para hacer setAttribute.