Harry Harry - 5 months ago 33
Javascript Question

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?

Javascript

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




HTML

<div class="appBanner">appbanner</div>





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

Answer

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 (el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
Comments