• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

34
Views
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>

about 1 month ago ·

Santiago Trujillo

1 answers
Answer question

0

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, 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 class="elm elm1"></div>
<div class="elm elm2"></div>
<div class="elm elm3"></div>

about 1 month ago · Santiago Trujillo Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.