ドキュメントオブジェクトのgetComputedStyle()メソッドと要素の属性フィールドを使用できます。
var oDiv = document.getElementById("div1");
var css = document.defaultView.getComputedStyle(oDiv, null);
var attr = oDiv.attributes;
これにより、要素が持つ各CSSスタイルのフィールドを持つオブジェクトが返されます。次に、単純な深さ優先のツリーウォークを記述して、DOM内のすべての要素を反復処理できます(追跡しやすいように、これをjQueryで記述しました)。
var stack = new Array();
stack.push($('html')[0]);
var i = 0;
while(stack.length > 0 && i < 100){
//pop the next element off the stack
var ele = stack.pop();
var css = document.defaultView.getComputedStyle(ele, null);
var attr = ele.attributes;
//do things with the css object
console.log(css);
//do things with the attributes
console.log(attr);
//add children to the stack
$(ele).children().each(function(index, child){
stack.push(child);
});
i++;
}
反復回数を100に制限し、ページに大量の要素がある場合にブラウザーを爆破しないようにするために、カウンター(i)をそこに配置していることに注意してください。必要に応じてこれを削除できますが、注意してください。また、検索のルートはDOM内の任意のノードにすることができますが、私はhtmlタグから始めたことにも注意してください。
あなたのコメントに基づいて、これをどのように実装するかについて説明します。CSS /属性オブジェクトをコンソールに出力するだけであることに注意してください。実際に実行したいことを実行するには、その部分を変更する必要があります。
脚本:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
function doStuff(){
var stack = new Array();
stack.push($('html')[0]);
var i = 0;
while(stack.length > 0 && i < 100){
//pop the next element off the stack
var ele = stack.pop();
var css = document.defaultView.getComputedStyle(ele, null);
var attr = ele.attributes;
//do things with the css object
console.log(css);
//do things with the attributes
console.log(attr);
//add children to the stack
$(ele).children().each(function(index, child){
stack.push(child);
});
i++;
}
}
</script>
それを実行するためのHTMLボタン
<button type="button" onclick="doStuff()">Click Me!</button>
完全な実装
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
function doStuff(){
var stack = new Array();
stack.push($('html')[0]);
var i = 0;
while(stack.length > 0 && i < 100){
//pop the next element off the stack
var ele = stack.pop();
var css = document.defaultView.getComputedStyle(ele, null);
var attr = ele.attributes;
//do things with the css object
console.log(css);
//do things with the attributes
console.log(attr);
//add children to the stack
$(ele).children().each(function(index, child){
stack.push(child);
});
i++;
}
}
</script>
</head>
<body>
<button type="button" onclick="doStuff()">Click Me!</button>
</body>
</html>
あなたがこれで何を成し遂げようとしているのか聞いてみたいです。これは遅い操作であり、通常、ページに配置したタグを調べることにはあまりメリットがありません...