Harry Harry - 3 months ago 14x
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?




<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.


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