Hide element by class in pure Javascript

JavascriptHtml

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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';

Solution 2 - Javascript

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

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

JSFiddle.

Solution 3 - Javascript

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

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

Solution 4 - Javascript

<script type="text/javascript">
        $(document).ready(function(){
           
                $('.appBanner').fadeOut('slow');
         
        });
    </script>

or

<script type="text/javascript">
        $(document).ready(function(){
           
                $('.appBanner').hide();
         
        });
    </script>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHarryView Question on Stackoverflow
Solution 1 - Javascriptc.P.u1View Answer on Stackoverflow
Solution 2 - Javascriptfederico-tView Answer on Stackoverflow
Solution 3 - JavascriptservermanfailView Answer on Stackoverflow
Solution 4 - JavascriptAli GüzelView Answer on Stackoverflow