Home > Net >  Use JavaScript to find element by its CSS property value
Use JavaScript to find element by its CSS property value

Time:04-15

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 ></div>
<div ></div>
<div ></div>

CodePudding user response:

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 ></div>
<div ></div>
<div ></div>

However, most of the time, yourr CSS is static, so you would know at the time of writing your JS code what the styles/selectors are that are responsible for stylying 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 ></div>
<div ></div>
<div ></div>

  • Related