DOMParser-获取元素样式

DOMParser - get element style

本文关键字:样式 元素 获取 DOMParser-      更新时间:2023-09-26

我正在尝试获取一个元素的样式属性,并使用DOMParser进行解析。不过,2个console.log显示为空。知道为什么会发生这种事吗?

<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);

getComputedStyle是一个仅对窗口可用的方法。由于您的代码位于DOM解析器内部,因此它没有正确的上下文,因此在该调用中返回空字符串。因此,这里有一种绕过它的方法。您可以获取有问题的元素,将其插入到窗口中,运行getComputedStyle,然后将其放回DOMParser(片段)中。

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>

您可以从以下答案中找到将RGB转换为HEX的解决方案