[英]How can i get specific element with 'document.querySelector' according to 'color' property?
I want to get the 'p' element with red color attribute.我想获得具有红色属性的“p”元素。 To do this i wrote the code below but i get a null result.为此,我编写了下面的代码,但结果为空。 What am i doing wrong?我究竟做错了什么?
test.html测试.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./test.css">
<script src="./test.js" defer></script>
<title>test</title>
</head>
<body>
<p id="p1">red</p>
<p id="p2">green</p>
<p id="p3">blue</p>
</body>
</html>
test.js测试.js
test.js
"use strict"
let element = document.querySelector("p[color='red']");
console.log(element); // logs null
test.css测试文件
#p1 {
color: red;
}
#p2 {
color: green;
}
#p3 {
color: blue;
}
You're trying to select an element based not on its HTML attributes , but on the CSS rules that are applied to it.您尝试选择的元素不是基于其HTML 属性,而是基于应用于该元素的 CSS 规则。 This can't be done with a plain querySelector
.使用普通的querySelector
无法做到这一点。
For the general case, iterate over all possibly matching elements and call getComputedStyle
on each to find the one that matches:对于一般情况,遍历所有可能匹配的元素并在每个元素上调用getComputedStyle
以找到匹配的元素:
const p = [...document.querySelectorAll('p')] .find(p => window.getComputedStyle(p).color === 'rgb(255, 0, 0)'); console.log(p);
#p1 { color: red; } #p2 { color: green; } #p3 { color: blue; }
<p id="p1">red</p> <p id="p2">green</p> <p id="p3">blue</p>
Note that for color, you need to use rgb
syntax.请注意,对于颜色,您需要使用rgb
语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.