在纯Javascript中按类隐藏元素 [英] Hide element by class in pure Javascript

查看:152
本文介绍了在纯Javascript中按类隐藏元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试了以下代码,但它不起作用。任何想法我错了?



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

< div class =appBanner> appbanner< / div>

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

解决方案

document.getElementsByClassName 返回一个 HTMLCollection (类似数组的对象)与类名匹配的所有元素。 样式属性定义为元素不适用于 HTMLCollection 。您应该使用括号(下标)符号访问第一个元素。

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


$ b >更新jsFiddle



使用Selectors API来更改所有匹配类的元素的样式规则:

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

如果 for 可用:

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


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.

解决方案

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

这篇关于在纯Javascript中按类隐藏元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆