Joe Defill
Joe Defill

Reputation: 499

Loop through all elements with a specific style

If I have a bunch of elements on the page with background-color: #000685; that have nothing in common (no common ids, classes, tag names etc,.).

Is there a way to loop through them all with JavaScript and change the background color value?

Upvotes: 4

Views: 1263

Answers (2)

You can add some attribute to make the targeting proccess easier:

<span 
    style="background-color: #FFFFFF;" 
    background-color
>
    Lorem ipsum dolor sit amet
</span>
<span>Lorem ipsum dolor sit amet</span>
<span 
    style="background-color: #FFFFFF;" 
    background-color
>
    Lorem ipsum dolor sit amet
</span>
<div>Lorem ipsum dolor sit amet</div>
<span 
    style="background-color: #FFFFFF;" 
    background-color
>
    Lorem ipsum dolor sit amet
</span>
<div>Lorem ipsum dolor sit amet</div>
<p 
    style="background-color: #FFFFFF;" 
    background-color
>
    Lorem ipsum dolor sit amet
</p>
<span 
    style="background-color: #FFFFFF;" 
    background-color
>
    Lorem ipsum dolor sit amet
</span>

js:

console.log(document.querySelectorAll('[background-color]'));

output:

// [object NodeList] (5)
["<span/>","<span/>","<span/>","<p/>","<span/>"] 

Upvotes: 0

Spectric
Spectric

Reputation: 32007

Since the elements have nothing in common, the best you can do is loop through every element on the page, get the background color for each one, and then perform checks. Like so:

var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++){
  var cur = elements[i];
  if(cur.style.backgroundColor=="rgb(0, 6, 133)"){
    cur.style.backgroundColor="red";
  }
}
<div style="background-color: #000685;">I should be red</div>
<div>I should not be red.</div>
<div style="background-color: #000685;">I should be red</div>
<div style="background-color: #000685;">I should be red</div>
<div>I should not be red.</div>
<div>I should not be red.</div>
<p style="background-color: #000685;">I should be red</p>
<p>I should not be red.</p>

If the style isn't inline, use getComputedStyle().getPropertyValue("background-color"):

var elements = document.getElementsByTagName("*");
for(let i = 0; i < elements.length; i++){
  var cur = elements[i];
  if(window.getComputedStyle(cur).getPropertyValue("background-color")=="rgb(0, 6, 133)"){
    cur.style.backgroundColor="red";
  }
}
.one{
  background-color: #000685;
}
.two{
  background-color: #000685;
}
.three{
  background-color:black;
  color:white;
}
<div class="one">I should be red</div>
<div>I should not be red.</div>
<div class="two">I should be red</div>
<div class="one">I should be red</div>
<div class="three">I should not be red.</div>
<div>I should not be red.</div>
<p class="two">I should be red</p>
<p class="three">I should not be red.</p>

Upvotes: 6

Related Questions