[javascript] Hide element by class in pure Javascript

I have tried the following code, but it doesn't work. Any idea where I have gone wrong?

_x000D_
_x000D_
document.getElementsByClassName('appBanner').style.visibility='hidden';
_x000D_
<div class="appBanner">appbanner</div>
_x000D_
_x000D_
_x000D_

Using jQuery or changing the HTML is not possible as I am using [self->webView stringByEvaluatingJavaScriptFromString:@""]; in Objective-C.

This question is related to javascript html

The answer is


document.getElementsByClassName returns an HTMLCollection(an array-like object) of all elements matching the class name. The style property is defined for Element not for HTMLCollection. You should access the first element using the bracket(subscript) notation.

document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';

Updated jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
  el.style.visibility = 'hidden';
});

If for...of is available:

for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';

Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

Forked @http://jsfiddle.net/QVJXD/


<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').fadeOut('slow');

        });
    </script>

or

<script type="text/javascript">
        $(document).ready(function(){

                $('.appBanner').hide();

        });
    </script>

var appBanners = document.getElementsByClassName('appBanner');

for (var i = 0; i < appBanners.length; i ++) {
    appBanners[i].style.display = 'none';
}

JSFiddle.