Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

205
Visualizações
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 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

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 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda