如何使用jQuery选择HTML页面中所有可见或隐藏的元素
为了使用jQuery选择页面中所有可见或隐藏的元素,我们可以使用以下jQuery选择器。
:visible选择器可见选择器用于选择当前文档中所有可见的元素。
- 语法:
$(":visible")
JavaScript
:hidden选择器 隐藏的选择器选择隐藏的元素来工作。
- 语法:
$(":hidden")
JavaScript
下面的例子说明了上述方法。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
How to select all visible
or hidden elements in a
HTML page using jQuery ?
</title>
<script src=
"https://code.jquery.com/jquery-1.12.4.min.js">
</script>
<style>
h1 {
color: green;
}
h4 {
color: green;
}
body {
text-align: center;
}
.geeks {
display: inline-block;
font: bold 16px sans-serif;
color: green;
}
.hidden {
display: none;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<h3>
How to select all visible or
hidden elements<br>in a HTML
page using jQuery
</h3>
<div class="geeks">GeeksforGeeks</div>
<div class="geeks hidden">
A Computer Sciecne Portal
</div>
<div class="geeks">For Geeks</div>
<div class="geeks hidden">
Learn Contribute Explore
</div>
<br>
<button type="button" class="visibleg">
Visible
<button type="button" class="hiddeng">
Hidden
<br>
<h4></h4>
<script>
(document).ready(function() {
(".visibleg").click(function() {
var visibleBoxes = [];
.each((".geeks"), function() {
if ((this).is(":visible")) {
visibleBoxes.push((this).text());
}
});
("h4").text("Visible items are - "
+ visibleBoxes.join(", "));
});
// Get hidden items
(".hiddeng").click(function() {
var hiddenBoxes = [];
.each((".geeks"), function() {
if ((this).is(":hidden")) {
hiddenBoxes.push((this).text());
}
});
$("h4").text("Hidden items are - "
+ hiddenBoxes.join(", "));
});
});
</script>
</body>
</html>
HTML
输出: