Gathering/Grouping different class divs

Hi everybody.

I have up to eight class divs.

<div class="element-1">The content of element A</div>
<div class="element-2">The content of element B</div>
...
<div class="element-8">The content of element B</div>

I cannot change their class name.

And a function that uses this script to apply a given style to them:

var elements = document.getElementsByClassName('element-1');
for(var i=0; i<elements.length; i++) { 
elements[i].style.display='block';
}

var elements = document.getElementsByClassName('element-2');
for(var i=0; i<elements.length; i++) { 
elements[i].style.display='block';
}
...

Is there any way to gather these scripts in a single one for the sake of file weight?

Thanks very much.

Weight here is extremely trivial. If you need to save weight, then run your code through a minifier. Smaller weight, doesn’t mean more readable. It’s usually the opposite.

document.querySelectorAll('[class*="element-"]').forEach(function(elm) {
    elm.style.display = 'block'
});

If I understood the question correctly, the above will do what you want. This will only support IE9+. It uses .querySelectorAll, which grabs elements by the CSS selector (simliiar to jQuery), and .forEach which asynchronously loops through the array.

Yes, I understand. Thanks mawburn.

1 Like

Check this. I made it on the fly but i hope to give you an idea

var a=[];
for(var x=1;x<8;x++){
    var b=a.push('element-'+[x]);
}

console.log(a);
for(var y=0;y<a.length;y++){
    var elements = document.getElementsByClassName(a[y]);
    for(var i=0; i<elements.length; i++) { 
        elements[i].style.display='block';
    }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.