.style is not canging element

Viewed 54

I have this script:

price2 = document.getElementById('price2');
price3 = document.getElementById('price3');

for (var i = 0; i < price2.length; i++) {
  price2[i].style.backgroundColor = 'orange';
}


<div class="single-car-prices">
  <div class="single-regular-price text-center" id="price2">
    <span class="labeled">Ціна</span>
    <span class="h3"> $ 1.500</span>
  </div>
</div>

Why color of this div is still blue:

output

There is no errors in console, I think I wrote JS correctly

2 Answers

getElementById takes always just one element. What you want is:

let price2 = document.getElementById('price2');
let price3 = document.getElementById('price3');


price2.style.color = 'orange';

UPDATE:

If you want to update background, then just use background property:

price2.style.background = 'orange';

An example:

let price2 = document.getElementById('price2');
let price3 = document.getElementById('price3');

price2.style.background = 'orange';
<div class="single-car-prices">
      <div class="single-regular-price text-center" id="price2">
        <span class="labeled">Ціна</span>
        <span class="h3"> $ 1.500</span>
      </div>
</div>

getElementById gives you back exactly one element, so there is no reason to use any sort of for loop.

Are you trying to style multiple elements with this id? Then id is the wrong way to go, use classes, id can only appear once on a page.

price2 = document.getElementById('price2');
price3 = document.getElementById('price3');

price2.style.color = 'orange';
<div class="single-car-prices">
  <div class="single-regular-price text-center" id="price2">
    <span class="labeled">Ціна</span>
    <span class="h3"> $ 1.500</span>
  </div>
</div>

Related