LoginSignup
3
0

More than 5 years have passed since last update.

再帰的にエレメントを辿って適応されているスタイルの値を取得する。

Last updated at Posted at 2017-07-19

地図ライブラリを使った時に、すべての要素に当たっている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に登録しておくと便利)

c0fed43b3e35e4613116e699fb6c8bb4-sni.png

任意のエレメントを指定すると、それ以下のエレメントに設定されてるスタイルを取得して配列として返す。

> 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の値が大きい順にソート

例)

c0fed43b3e35e4613116e699fb6c8bb4.png

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0