Javascript:按类名隐藏元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3560764/
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
Javascript: Hide elements by class name
提问by lewisqic
I have an html element that I want to hide from view, but I can't access that element by an ID because it has no ID and I can't assign an ID to it. It has a class assigned to it though. Is there any possible way to hide this element from view without having it's id?
我有一个想要隐藏的 html 元素,但我无法通过 ID 访问该元素,因为它没有 ID,我无法为其分配 ID。不过,它有一个分配给它的类。有没有办法在没有它的 id 的情况下隐藏这个元素?
采纳答案by dxh
There's getElementsByClassNamein some browsers, but it's not as widely supported as getElementById. Note that it yields an array of elements, instead of just a single element, as several elements can have the same class.
还有getElementsByClassName在一些浏览器,但它没有被广泛支持的getElementById。请注意,它产生一个元素数组,而不仅仅是单个元素,因为多个元素可以具有相同的类。
If you can assign an ID to a parent you might be able to access it in some other way:
如果您可以将 ID 分配给父级,则可以通过其他方式访问它:
document.getElementById('parent').getElementsByTagName('div')[3] // or whatever
回答by Naveen
The following html file contains code to toggle, hide, show div by class and id. By using class it is possible to hide a set(group) of divisions.
以下 html 文件包含按类和 id 切换、隐藏、显示 div 的代码。通过使用类,可以隐藏一组(组)分区。
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
/*function to toggle visibility of class*/
function toggle_visibility(classname) { $("."+classname).toggle(); }
/*function to hide class*/
function hide_visibility(classname) { $("."+classname).hide(); }
/*function to show class*/
function show_visibility(classname) { $("."+classname).show(); }
/*function to hide individual div by id*/
function hide_visibility(classname) { $("#"+classname).hide(); }
/*function to show individual div by id*/
function show_visibility(classname) { $("#"+classname).show(); }
</script>
</head>
<body>
<button onclick="toggle_visibility('class1');">Toggle visibility of class 1</button><br/>
<button onclick="hide_visibility('class1');">Hide class 1</button><br/>
<button onclick="show_visibility('class1');">Show class 1</button><br/>
<button onclick="show_visibility('heading1');">Show heading 1</button><br/>
<button onclick="hide_visibility('heading1');">Hide heading 1</button><br/>
<div class="class1" id="heading1"><h1>Heading 1</h1></div>
<div class="class1"><h2>Heading 2</h2></div>
<div class="class1"><h3>Heading 3</h3></div>
<div class="class1"><h4>Heading 4</h4></div>
<div class="class1"><h5>Heading 5</h5></div>
<div class="class1"><h6>Heading 6</h6></div>
</body>

