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
CodePudding user response:
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.