Backslash Backslash - 3 months ago 18
HTML Question

DOMParser - get element style

I'm trying to get a style property of an element that I parse with DOMParser. The 2 console.logs come up empty though. Any idea why this happens?

<div id='foobar'>
<style>
.xl496
{
color:#336699;
}
</style>

<table>
<tr>
<td class='xl496'>Test:</td>
</tr>
</table>
</div>





var data = document.getElementById("foobar");

var parser = new DOMParser();
var doc = parser.parseFromString(data.innerHTML, "text/html");
var cols = doc.getElementsByTagName("tr");
var col = cols[0];
var tds = col.getElementsByTagName("td");
var td = tds[0];

console.log(getComputedStyle(td).getPropertyValue("color"));
console.log(td.style.color);

Answer

getComputedStyle is a method that is only available to the window. Since your code is inside of a DOM parser, it does not have the right context, and therefore returns empty strings back in that call. So, here is a way to get around it. You can take the element in question, insert it into the window, run the getComputedStyle and then put it back into the DOMParser (fragment).

var clipboardData = document.getElementById("foobar").outerHTML;


var parser = new DOMParser();
var doc = parser.parseFromString(clipboardData, "text/html");

var col = doc.querySelector("tr");
var td = col.querySelector("td");

// td has to be in the window, not a fragment in order to use window.getComputedStyle
document.body.appendChild(td);

console.log(window.getComputedStyle(td).getPropertyValue("color"));
// the next one expected to be "" since it does not have inline styles
console.log(td.style.color);

// Insert the td back into the dom parser where it was
col.insertBefore(td, col.firstChild);
<div id='foobar'>
  <style>
    .xl496 {
      color: #336699;
    }
  </style>

  <table>
    <tr>
      <td class='xl496'>Test:</td>
    </tr>
  </table>
</div>

You can look at a solution to convert RGB to HEX with something from this answer

Comments