在纯 Javascript 中按类隐藏元素

我已经尝试了下面的代码,但它 没用。有任何想法,我在哪里错了吗?

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

使用 jQuery 或更改 HTML 是不可能的,因为我在 Objective-C 中使用的是 [self->webView stringByEvaluatingJavaScriptFromString:@""];

298783 次浏览

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';
var appBanners = document.getElementsByClassName('appBanner');


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

JSFiddle.

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

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

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


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


});
</script>

or

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


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


});
</script>