Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide element by class in pure Javascript [duplicate]

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.

like image 807
Harry Avatar asked Aug 24 '13 02:08

Harry


People also ask

How do you hide an element in JavaScript?

Style display property is used to hide and show the content of HTML DOM by accessing the DOM element using JavaScript/jQuery. To hide an element, set the style display property to “none”.

What is hide () in JavaScript?

The hide() method hides the selected elements. Tip: This is similar to the CSS property display:none. Note: Hidden elements will not be displayed at all (no longer affects the layout of the page). Tip: To show hidden elements, look at the show() method.

How do I hide the P tag in HTML?

Use display:none to hide an element, it will not be available in the page and does not occupy any space. Use visibility:hidden to hide an element, it will still take up the same space as before when visible.


1 Answers

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'; 
like image 102
c.P.u1 Avatar answered Sep 21 '22 09:09

c.P.u1