Change Style for Multiple Elements onClick: getElementById, getElementsByClassName, querySelectorAll oh my

Minnesota Web Developer

A little something about everything...

Change Style for Multiple Elements onClick: getElementById, getElementsByClassName, querySelectorAll oh my

With a bit of creative javascript and these Methods you can do some pretty neat stuff.

On this page I've create an example for multiple elements display block/none function based onclick function. You could also utilize checkbox.checked, onmouseover, or other such functions.

You can replace querySelectorAll with getElementsByClassName or getElementById for broader browser support or you can simply create a detector onload to look for an element on the page and hide it if the Method is supported with querySelector like this:

window.onload = function(){
 document.querySelector('#compat').style.display = 'none';
    }

The Code:

HTML

<div class="aa" style="display: block;">class: aa, no id</div>
<div class="aa" id="aa" style="display: block;">class: aa, id: aa</div>
<div class="bb" style="display: block;">class: bb, no id</div>
<div id="aa" style="display: block;">no class, id: aa</div>
<a onclick="showClass('.aa');" href="#">Looks for class: aa</a>
<a onclick="showClass('#aa, .bb');" href="#">Looks for class: bb, and id: aa</a>
<a onclick="showClass('.aa, .bb');" href="#">Looks for class: aa, bb</a>
<div id="compat" style="display:block;position:absolute;width:100%;height:100%;background-color:#fff;top:0;left:0;padding:50px; "><h1>Compatability Error!</h1>
<p>This page uses newer coding technologies. You should consider upgrading your browser.</p>
<p>for suggestions, please go <a href="http://outdatedbrowser.com/en">here</a>.</p>
<a href="#" onClick="document.getElementById('compat').style.display = 'none';">Continue Anyways</a>

Javascript

function showClass(s){
 var e = [];
 var e = document.querySelectorAll(s);
 for (var i = 0; i < e.length; i++){
    if(!e[i])return true;

    if(e[i].style.display=="none"){
       e[i].style.display="block"
    } else {
       e[i].style.display="none"
    }
 }
 return true;
}

Use your imagination and see what you can do with it.

Here is a working example:

class: aa, no id
class: aa, id: aa
class: bb, no id
no class, id: aa
Looks for class: aa Looks for class: bb, and id: aa Looks for class: aa, bb

Compatability Error!

This page uses newer coding technologies. You should consider upgrading your browser.

for suggestions, please go here.

Continue Anyways
Loading