简体   繁体   English

如何根据“color”属性获取带有“document.querySelector”的特定元素?

[英]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.

相关问题 如何将我的表单与document.querySelector相关联? - How can I associate my form with document.querySelector? 如何使用`document.querySelector()`访问ExtJS元素? - How can I access ExtJS elements using `document.querySelector()`? document.querySelector() 可以根据 SRC 文件名(而不是完整的 URL)查找 IMG 元素吗? - Can document.querySelector() Find an IMG Element According to a SRC FileName (instead of full URL)? 如何实现document.querySelector? - How is document.querySelector implemented? 如何使用元素 document.querySelector 更改样式 - How to change style using element document.querySelector 如何确定我是选择document.querySelector的多个元素还是单个元素 - How to determine if I'm selecting multiple or a single element with document.querySelector 我不能添加超过 2 个 document.querySelector().addEventListener() - I can't add document.querySelector().addEventListener() more than 2 如何将 document.querySelector 用于 select 这个 class 名称,其中有空格? - How can I use document.querySelector to select this class name with a space in it? 为什么document.querySelector在伪元素上不起作用? - Why is document.querySelector not working on pseudo element? 如何对具有 document.querySelector 的 function 进行单元测试? - How do i unit test a function that has document.querySelector?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM