0

So, I have a selector which matches a <td>. This <td> inherits from a css class. Let's call it item.

item.style.backgroundImage

returns "", but

window.getComputedStyle(item).backgroundImage

returns

"url("http://some-url.com")"

I want to modify the css class so that the backgroundImage is something else for all inheritors.

I haven't been able to figure out how to do this! I can change the backgroundImage of the individual element, but I don't know how to get the class object that defines backgroundImageoriginally.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
Daniel Paczuski Bak
  • 3,720
  • 8
  • 32
  • 78

3 Answers3

0

Write new CSS for target class and put it in <style> and append it to head tag.

var style = '<style>.item {background: red !important}</style>';
document.querySelector('head').innerHTML += style;
.item {
  width: 50px;
  height: 50px;
  border: 1px solid #000;
  background: green;
}
<div class="item"></div>
<div class="item"></div>
Mohammad
  • 21,175
  • 15
  • 55
  • 84
0

You can use unset to reset the inherited property. See the snippet below. The second cell (whose id is dontInherit) won't receive the background-color property.

td {
  background-color: #f0f0ff;
}

td#dontInherit {
  background-color: unset;
}
<table>
  <tr>
    <td id="inherit">
      Inherited
    </td>
    <td id="dontInherit">
      Not inherited
    </td>
  </tr>
</table>
Amessihel
  • 5,891
  • 3
  • 16
  • 40
0

I would add one more thing to @Mohammad's answer.

If you want it for dynamic class then you can get the className and change it's style and add it to head tag.

See the Snippet below:

var item = document.querySelector("#itemA");

var style = '<style>.'+item.className+' {background-image: url("https://www.beautycolorcode.com/8b0000.png") }</style>';

document.querySelector('head').innerHTML += style;
td{
  background-image: url('https://www.beautycolorcode.com/3a4662.png');
  color:white;
  width:300px;
  height:40px;
  font-family:"Calibri";
}
<table>
  <tr><td id="itemA" class="item-A">A for Apple</td></tr>
  <tr><td class="item-B">B for Ball</td></tr>
  <tr><td class="item-C">C for Cat</td></tr>
  <tr><td class="item-A">A for Ant</td></tr>
</table>

You can see by default it's blue color background image. I have changed it to red color for .item-A class dynamically using ID selector.

Nimitt Shah
  • 4,477
  • 2
  • 10
  • 21