2016-08-03 8 views
3

私はDOMParserで解析する要素のスタイルプロパティを取得しようとしています。しかし、2つのconsole.logが空になります。なぜこのようなことが起こるのか?DOMParser - 要素スタイルを取得

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

から何かをHexにRGBを変換するためのソリューションを見ることができますが、DOMParserにを使用する必要がありますか? – KevBot

+0

はい。後で私はクリップボードからこのe.clipboardData.getData( 'text/html')のようなデータを取得する予定です。 – Backslash

答えて

2

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>

あなたはthis answer

+0

私はそれをすることができた。しかし、次のステップとしてクリップボード統合を追加する予定です。ですから、私はe.clipboardData.getData( 'text/html')からデータを取得します。 – Backslash