0

I want to select a bunch of spans in a div whose CSS contains a particular background colour. How do I achieve this?

(This is the same question with this question, except I'm looking for non-jQuery solution.)

MongoLato
  • 351
  • 2
  • 20

2 Answers2

0
  var new_elemt =[];
  (function() {

  // Get all elements that have a style attribute
  var elms = document.querySelectorAll("*[style]");

  // Loop through them
  Array.prototype.forEach.call(elms, function(elm) {
    // Get the color value
    var clr = elm.style.backgroundColor || "";

   if(clr!=""){
   new_elemt.push(elm);
   }

   
  });
})();
Hammad Ahmed khan
  • 1,618
  • 7
  • 19
0

// Get all spans
let spans = document.querySelectorAll('div#someDiv span'); 

// Convert spans nodeslist to array
spans = Array.from( spans ); 

// Filter spans array
// Get CSS properties object of selected element - [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle)
let arr = spans.filter( span => String( document.defaultView.getComputedStyle( span, null ).backgroundColor ) == 'rgb(0, 0, 0)' );

// Change background color of matched span elements
arr.forEach( span => {
    span.style.backgroundColor = 'green';
});
.one, .two {
  background-color: black;
}

.three {
  background-color: red;
}
<div id="someDiv">
    <span class="one">test one</span>
    <span class="two">test two</span>
    <span class="three">test three</span>
</div>