Javascript ,compare the background of a div by DOM

Asked

Viewed 31 times

0

Good morning gentlemen and ladies,I’m making a comparison to change the color of a div if she has a background Yellow for green but I don’t understand why it’s not working

function exerciseTwo() {
    let tagDiv = document.getElementsByTagName('div');
    for(let i = 0; i < tagDiv.length; i += 1) {
            if(tagDiv[i].style.backgroundColor == 'yellow') {
                tagDiv[i].style.backgroundColor = 'green';
      }
    }
}
exerciseTwo();
  • 1

    Gabriel add tbm html to the question

1 answer

1


The element.style only allows you to access the specific styles of the element, that is, whatever is inside its style attribute. Use the window.getComputedStyle() to pick up the applied styles. In your code it would be:

window.getComputedStyle(tagDiv[i]).getPropertyValue('background-color')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.