Search code examples
javascripthtmlcsslegacy

Search and replace legacy background color


I'm working with some old HTML and CSS...

The code looks something like this:

<html>
<head>
<style>
table.highlight {
    BACKGROUND: yellow;
}
</style>
</head>
<table class="highlight"><tr><td>test</td></tr></table>
</html>

Assuming the DOM code is read-only and the only fix is a code snippet that runs after the DOM has loaded, how would one hunt down these "yellow" colors and replace them?

I've tried to look for <table>.style.BACKGROUND, <table>.style.background and <table>.style.backgroundColor to no avail yet the color appears correctly in the web browser.

When I echo the contents of <table>.style yellow doesn't appear anywhere. Is there a way to access these old, legacy CSS components?

I can successfully change the color by setting <table>.style.backgroundColor, but I'm having trouble locating the yellow to begin with. All attempts to read the CSS return blank.

I'm testing in Google Chrome and Firefox. Both return undefined or "".


Solution

  • you can use getComputedStyle

    [...document.querySelectorAll('table')].forEach(e => {
      // if the background-color is yellow then change it to red
      if (getComputedStyle(e)['background-color'] === 'rgb(255, 255, 0)') 
        e.style.backgroundColor = 'red'
    })
    <html>
    
    <head>
      <style>
        table.highlight {
          BACKGROUND: yellow;
        }
        
        table.highlight2 {
          BACKGROUND: green;
        }
      </style>
    </head>
    <table class="highlight">
      <tr>
        <td>test</td>
      </tr>
    </table>
    <table class="highlight">
      <tr>
        <td>test</td>
      </tr>
    </table>
    <table class="highlight2">
      <tr>
        <td>test</td>
      </tr>
    </table>
    
    </html>