nakar20966
nakar20966

Reputation: 133

Use JavaScript to find element by its CSS property value

How do I find the element by matching its CSS property value?

For example, if the background color of the element is green, then do something...

const elm = document.getElementsByClassName('elm');

[...elm].forEach(function(s) {
  //find the element which background color is green
  
  //then console.log(theItem)
})
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

Upvotes: 1

Views: 401

Answers (2)

Nick Parsons
Nick Parsons

Reputation: 50759

You can use the window.getComputedStyle() method on each of your elements to check and see if an element has your green background colour. For the green colour, the computed style for this is the RGB colour of rgb(0, 128, 0). By using .filter() you can return a new array of elements that have a computed background color of this value:

const elm = document.getElementsByClassName('elm');

const greenElms = [...elm].filter(function(s) {
  const bgColor = getComputedStyle(s).backgroundColor;
  return bgColor === "rgb(0, 128, 0)";
});
console.log(greenElms);
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

However, most of the time, your CSS is static, so you would know at the time of writing your JS code what the styles/selectors are that are responsible for styling your elements, and so you can instead use .querySelectorAll() to match the same elements that the green background style is applying to, eg:

const greenElms = document.querySelectorAll('.elm2'); // NodeList (similar to an array)
console.log(greenElms);
.elm {
  width: 200px;
  height: 100px;
}

.elm1 {
  background-color: red;
}

.elm2 {
  background-color: green;
}

.elm3 {
  background-color: blue;
}
<div class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

Upvotes: 1

Leo Caseiro
Leo Caseiro

Reputation: 1845

Based on Nick Parsons answer, I came up with a way to search any property in any element:

const searchByProperty = (property) =>
    Array.from(document.querySelectorAll('*')).filter((s) => {
        const value = getComputedStyle(s)[property];
        console.log(property, value);
    });

Usage:

searchByProperty('backgroundColor');

Upvotes: 0

Related Questions