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.)
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.)
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);
}
});
})();
// 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>