Html 在纯Javascript中按类隐藏元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18414384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:32:14  来源:igfitidea点击:

Hide element by class in pure Javascript

javascripthtml

提问by Harry

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.

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

回答by c.P.u1

document.getElementsByClassNamereturns an HTMLCollection(an array-like object) of all elements matching the class name. The styleproperty is defined for Elementnot for HTMLCollection. You should access the first element using the bracket(subscript) notation.

document.getElementsByClassName返回HTMLCollection与类名匹配的所有元素的(一个类似数组的对象)。该style属性被定义为Elementnot for HTMLCollection。您应该使用括号(下标)表示法访问第一个元素。

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

Updated jsFiddle

更新了 jsFiddle

To change the style rules of all elements matching the class, using the Selectors API:

要更改与该类匹配的所有元素的样式规则,请使用 Selectors API:

[].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
  el.style.visibility = 'hidden';
});

If for...ofis available:

如果for...of可用:

for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';

回答by federico-t

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

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

JSFiddle.

JSFiddle。

回答by servermanfail

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

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

分叉@ http://jsfiddle.net/QVJXD/

回答by Ali Güzel

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

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

        });
    </script>

or

或者

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

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

        });
    </script>