Mesut Çiftçi
Mesut Çiftçi

Reputation: 160

How can i get specific element with 'document.querySelector' according to 'color' property?

I want to get the 'p' element with red color attribute. To do this i wrote the code below but i get a null result. What am i doing wrong?

test.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

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;
}

Upvotes: 1

Views: 1006

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370729

You're trying to select an element based not on its HTML attributes, but on the CSS rules that are applied to it. This can't be done with a plain querySelector.

For the general case, iterate over all possibly matching elements and call getComputedStyle on each to find the one that matches:

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.

Upvotes: 2

Related Questions