地図ライブラリを使った時に、すべての要素に当たっているz-indexの値を知りたい時があったので、指定したエレメント以下を再帰的に辿りスタイルの値を取得するスニペットを書いた。
function getProperty(element, key) {
var traverse = function(obj){
var tree = [];
tree.push(obj);
visit(obj);
function visit(node) {
if (node && node.hasChildNodes()) {
var child = node.firstChild;
while (child) {
if (child.nodeType === 1 && child.nodeName != 'SCRIPT'){
tree.push(child);
visit(child);
}
child = child.nextSibling;
}
}
}
return tree;
};
var tree = traverse(element);
var propertys = tree.map(function(d){
return {element:d, value:getComputedStyle(d).getPropertyValue("z-index")};
});
return propertys;
}
上記ファンクションをコンソールに流し込んで使う。
(chromeならsnippetsに登録しておくと便利)
任意のエレメントを指定すると、それ以下のエレメントに設定されてるスタイルを取得して配列として返す。
> getProperty(document.querySelector("body"), "z-index")
出力結果を多少整理してあげると読みやすいかも
getProperty(document.querySelector("body"), "z-index") //body以下のz-indexを取得
.filter(function(d){ return !isNaN(+d.value )}) //z-indexの値が数値以外は対象外に
.map(function(d){ return [d.element, d.value] }) //エレメント名とz-indexの値を抽出
.sort(function(a, b){ return b[1] - a[1] }) //z-indexの値が大きい順にソート
例)