Skip to content Skip to sidebar Skip to footer

How To Make CSS Styles Override JavaScript Applied Styles

I create an HTML table dynamically, and apply some styles: var tbl = document.createElement('table'); tbl.id = 'CrewMemberTable'; document.getElementById('CrewMemberPanel').appen

Solution 1:

You will need a selector with greater specificity, such as

#CrewMemberTable tr:hover, #CrewMemberTable tr:hover td {
    background-color: RED !important;
}

You will particularly want to target the cell in addition to the row. (If you wanted you could add a class or id to the cell to facilitate higher-specificity targeting.)

See snippet below for a working example using the code structure you have provided in your question:

var tbl = document.createElement('table');
tbl.id = "CrewMemberTable";
document.getElementById("CrewMemberPanel").appendChild(tbl);
CrewRow = document.getElementById("CrewMemberTable").insertRow(-1);
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "this text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "some text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "more text";
CrewCell = CrewRow.insertCell(-1); CrewCell.innerHTML = "more text";
CrewCell.style.backgroundColor = "GREEN";
#CrewMemberTable tr:hover, #CrewMemberTable tr:hover td {
        background-color: RED !important;
    }
<div id="CrewMemberPanel"></div>

Solution 2:

The problem is, you're only targeting the <tr> with CSS but the GREEN background is on the <td>.

Add this to your CSS

#CrewMemberTable tr:hover td {
  background-color: transparent !important;
}

Demo

#CrewMemberTable tr:hover {
  background-color: RED !important;
}

#CrewMemberTable tr:hover td {
  background-color: transparent !important;
}
<div id="CrewMemberPanel">
  <table id="CrewMemberTable">
    <tr>
      <td>this text</td>
      <td>some text</td>
      <td style="background-color: GREEN">more text</td>
    </tr>
  </table>
</div>

Post a Comment for "How To Make CSS Styles Override JavaScript Applied Styles"