如何用jQuery选择包含某些特定CSS属性的所有元素
给定一个包含元素的HTML文档,一些元素有特定的CSS属性。任务是选择所有具有相同属性值对的元素。有两种方法,将在下面讨论。
方法1:首先使用jQuery选择器选择我们要检查的相同属性的元素。在每个元素上使用filter()方法,如果特定的CSS属性与它的CSS匹配,则返回值为true。现在,我们有了所有具有相同CSS属性值对的元素。获取它们的ID以确定哪些元素被选中。
- 例子。这个例子实现了上述方法。
<!DOCTYPE html>
<html>
<head>
<title>
How to select all elements that contains
some specific CSS property using jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p id="gfg" style=
"font-size: 20px;font-weight: bold;">
Click on the button to get the ID's
of selected elements having same
property value pair.<br>CSS-
'font-weight: bold'
</p>
<button onclick="GFG_Fun();">
Click Here
<p id="geeks" style=
"font-size: 24px; font-weight: bold;
color: green;">
</p>
<script>
var down = document.getElementById('geeks');
function GFG_Fun() {
var x = $('p').filter(function() {
return this.style.fontWeight == 'bold'
});
down.innerHTML = "ID's of selected "
+ "elements are - <br>" + x[0].id
+ "<br>" + x[1].id;
}
</script>
</body>
</html>
- 输出:
方法2:首先使用jQuery选择器选择我们要检查的相同属性的元素。在每个元素上使用not()方法,如果特定的CSS属性与它的CSS不匹配,返回值为true。现在,我们有所有具有相同CSS属性的元素,获取它们的ID来确定哪些元素被选中。
- 例子。这个例子实现了上述方法。
<!DOCTYPE html>
<html>
<head>
<title>
How to select all elements that contains
some specific CSS property using jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1 style="color:green;">
GeeksforGeeks
</h1>
<p id="gfg" style="font-size: 20px;
font-weight: bold;">
Click on the button to get the
ID's of selected elements having
same property value pair.<br>CSS-
'font-size: 20px'
</p>
<button onclick="GFG_Fun();">
Click Here
<p id="geeks" style=
"font-size: 20px; font-weight: bold;
color: green;">
</p>
<script>
var down = document.getElementById('geeks');
function GFG_Fun() {
/* Using not method, which removes
the elements which don't matches
the property. */
var x = ('p').not(function() {
return(this).css('font-size') != '20px';
});
down.innerHTML = "ID's of selected "
+ "elements are - <br>" + x[0].id
+ "<br>" + x[1].id;
}
</script>
</body>
</html>
- 输出: