I am trying to get multiple elements, that are organised under 3 arrays “tops”, “bottoms”, “shoes”.
I know I can grab multiple objects using the
document.getElementsByClassName("class1 class2");
How do I change the style for each of those objects, my current code is: (I have tried both visibility and opacity, but it keep getting a uncaught type error because the document.getelements…. isn’t returning anything.
function filter() {
var this_id = event.target.id;
console.log(this_id);
if (this_id = "filtertops") {
document.getElementsByClassName("a4 a7 a11 a12 a8").style.visibility="hidden"; //not tops
document.getElementsByClassName("a1 a2 a3 a5 a9 a10 a14").style.visbility="visible"; // tops
}
else if (this_id = "filterbottoms") {
document.getElementsByClassName("a2 a3 a5 a10 a14 a8").style.opacity="0.4"; //not bottoms
document.getElementsByClassName("a1 a4 a7 a9 a11 a12").style.opacity="1"; //bottoms
}
else if (this_id = "filtershoes") {
document.getElementsByClassName("a1 a2 a3 a4 a5 a7 a9 a10 a11 a12 14").style.opacity="0.4"; //not shoes
document.getElementsByClassName("a8").style.opacity="1"; //shoes
}
I tried assigning them to a variable as well and then a for loop to change the style of each object, but that didnt work either.
function filterbottoms() {
var nonbottom = document.getElementsByClassName("a2 a3 a5 a10 a14 a8");
var bottoms = document.getElementsByClassName("a1 a4 a7 a9 a11 a12");
for (i in bottoms)
{
i.style.visibility='visible';
}
for (i in nonbottom)
{
i.style.visibility='hidden';
}
}
You were close with the
forloop:should
<edit>but won’t</edit>work. On each iterationiis the next key, not the next value.But you should use a conventional
forrather than afor..in:EDIT: I recommended a conventional
forloop because usingfor..inis generally not appropriate for arrays or array-like objects as (depending on the particular object) it will iterate over non-numeric properties. Joseph’s comment confirms that in this case afor..inwill definitely not work for that reason.