Change style of all elements using getElementsByTagName()

pancakes picture pancakes · Jun 27, 2013 · Viewed 25.8k times · Source

I'm fairly new to javascript and have been unable to get this code to work and I am unsure were and what I'm missing.

So here is what I want it to do. I'm trying to have the script read everything and switch the visibility of the span found in the body

<body> 
   <span hidden>A</span>     
   <span>X</span>
   <span hidden>B</span>
   <span>Y</span>
   <span hidden>C</span>
   <span>Z</span>
</body>

So instead of reading 'X Y Z' it will display 'A B C'

The code I have so far is..

$(function() {

    var elems = document.getElementsByTagName('span');

    for (var i = 0; i<elems.length; i++) {
        if (elems[i].style.visibility == 'visible') {
            elems[i].style.visibility = 'hidden';    
        }
        else {
            elems[i].style.visibility = 'visible';
        }
    }

});

Here is the jsfiddle of my code. I would greatly appropriate some feedback or possible threads that might point me in the right direction.

Answer

user2437417 picture user2437417 · Jun 27, 2013

You're using the HTML5 hidden attribute, so you should just reverse that property.

for (var i = 0; i<elems.length; i++) {
    elems[i].hidden = !elems[i].hidden;
}

DEMO: http://jsfiddle.net/TEXJp/


If you were to use the style object, then you need to consider that it will only report styles that were set directly on the element. So your test should be for == "" instead of == "visible", or for == "hidden" if you actually set it on the original elements.

<span style="visibility:hidden;">H</span>   
<span>V</span>

<span style="visibility:hidden;">H</span>
<span>V</span>

var elems = document.getElementsByTagName('span');

for (var i = 0; i < elems.length; i++) {
    if (elems[i].style.visibility === "hidden") {
        elems[i].style.visibility = "visible";
    } else {
        elems[i].style.visibility = "hidden";
    }
}

DEMO: http://jsfiddle.net/TEXJp/1/