92

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

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

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

hichris123
  • 10,145
  • 15
  • 56
  • 70
Harry
  • 3,301
  • 7
  • 27
  • 33
  • 3
    getElementsByClassName returns an array of elements. You need something like: document.getElementsByClassName('appBanner')[0].style.visibility='hidden'; – bitfiddler Aug 24 '13 at 02:45

4 Answers4

158

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';
c.P.u1
  • 16,664
  • 6
  • 46
  • 41
48
var appBanners = document.getElementsByClassName('appBanner');

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

JSFiddle.

mattes
  • 8,936
  • 5
  • 48
  • 73
federico-t
  • 12,014
  • 19
  • 67
  • 111
  • I beginner on JS, but why you write `, i;` on first line? This used in for cycle? ( but we declare `i` in cycle later ) Or it small mistake? Or maybe its some "best practice"? Could you comment it, please. – Denis Savenko Jun 10 '16 at 11:52
  • 1
    @DenisSavenko it's simply declaring a second var. – Sarima Jul 05 '16 at 14:18
  • 4
    @DenisSavenko - It's valid `var` syntax to declare multiple variables separated by commas, but in this case it is a mistake to then *also* declare `i` with `var` in the `for` loop - though this doesn't actually cause an error, it's just untidy. – nnnnnn Oct 07 '16 at 05:19
  • cute answer bro...i like it –  Oct 07 '16 at 05:44
-2
Array.filter( document.getElementsByClassName('appBanner'), function(elem){ elem.style.visibility = 'hidden'; });

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

JON
  • 965
  • 2
  • 10
  • 28
servermanfail
  • 2,532
  • 20
  • 21
-4
<script type="text/javascript">
        $(document).ready(function(){

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

        });
    </script>

or

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

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

        });
    </script>
Ali Güzel
  • 85
  • 12
  • 6
    The OP does not mention jQuery – StudioTime Sep 06 '16 at 10:52
  • – Quang Minh Sep 02 '21 at 10:43