[英]How can I use getElementsByClassName(<classname>).outerHTML="" to hide a <div> when there are multiple names for the div's class?
I am trying to learn how to hide <div>
sections on a webpage, using javascript getElementsByClassName("<classname>").outerHTML=""
.我正在尝试学习如何使用 javascript
getElementsByClassName("<classname>").outerHTML=""
在网页上隐藏<div>
部分。
It all works great if the element I am hiding eg <div class="someclassname">Some content I want to hide</div>
.如果我要隐藏的元素例如
<div class="someclassname">Some content I want to hide</div>
,这一切都很好。 Or, I have success if using getElementByID("<divId>")
if working with eg <div id="somedivID">
.或者,如果使用
getElementByID("<divId>")
如果使用例如<div id="somedivID">
,我会成功。
The problem is, when wanting to hide a <div>
that has no id
and when there are multiple names listed for the div's class such as below:问题是,当想要隐藏没有
id
的<div>
并且为 div 的 class 列出多个名称时,如下所示:
<div class="cake forest carousel">Some content I want to hide.</div>
How can I hide such a div that has not id and no single class name?如何隐藏这样一个没有 id 且没有单个 class 名称的 div?
For classes, you can use document.querySelectorAll()
along with css selectors, like this:对于类,您可以将
document.querySelectorAll()
与 css 选择器一起使用,如下所示:
document.querySelector('button').addEventListener('click', () => { document.querySelectorAll('.cake')[0].style.display = 'none'; });
<div class="cake forest carousel">Some content I want to hide.</div> <button>Hide content</button>
With classNames, remember that you can specify ALL the classNames (sometimes that is useful to pinpoint one element if there are other elements that contain part of the classList:使用 classNames,请记住您可以指定所有的 classNames(如果有其他元素包含 classList 的一部分,有时这对于查明一个元素很有用:
document.querySelectorAll('.cake.forest.carousel')[0] . . .
Also note that document.querySelectorAll()
returns a collection , not a string - which is why it is necessary to use the [0]
notation to choose the first element returned in the collection.还要注意
document.querySelectorAll()
返回一个集合,而不是一个字符串——这就是为什么必须使用[0]
符号来选择集合中返回的第一个元素的原因。
Using getElementsByClassName()
is much the same idea - again, it returns a collection and one must either use the [0]
notation to get the first element (usually if only one is returned), or a forEach()
loop to choose the desired element based on other criteria.使用
getElementsByClassName()
的想法大致相同 - 同样,它返回一个集合,并且必须使用[0]
表示法来获取第一个元素(通常如果只返回一个元素),或者使用forEach()
循环来选择所需的基于其他标准的元素。
document.querySelector('button').addEventListener('click', () => { document.getElementsByClassName('cake forest')[0].style.display = 'none'; });
<div class="cake forest carousel">This div has classes cake, forest and carousel</div> <div class="cake">This div only has class cake</div> <button>Hide divs with classes cake AND forest</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.