js 获取dom树 或 css路径

document.addEventListener("click", function (clickEvent) {
            let target = clickEvent.target;
            readXPath(target)
 });
function readXPath(el) {
    // jq路径
    // if (!el) {
    //     return;
    // }
    // let stack = [];
    // let isShadow = false;
    // while (el.parentNode != null) {
    //     let sibCount = 0;
    //     let sibIndex = 0;
    //     for ( let i = 0; i < el.parentNode.childNodes.length; i++ ) {
    //         let sib = el.parentNode.childNodes[i];
    //         if ( sib.nodeName === el.nodeName ) {
    //             if ( sib === el ) {
    //                 sibIndex = sibCount;
    //             }
    //             sibIndex = sibCount;
    //             sibCount++;
    //         }
    //     }
    //     let nodeName = el.nodeName.toLowerCase();
    //     if (isShadow) {
    //         nodeName += "::shadow";
    //         isShadow = false;
    //     }
    //     if ( sibCount > 1 ) {
    //         stack.unshift(nodeName + ':eq(' + (sibIndex + 1) + ')');
    //     } else {
    //         stack.unshift(nodeName);
    //     }
    //     el = el.parentNode;
    //     if (el.nodeType === 11) {
    //         isShadow = true;
    //         el = el.host;
    //     }
    // }
    // return stack.join(' > ');

    // 标准CSS路径
    if (!(el instanceof Element))
        return;
    let path = [];
    while (el.nodeType === Node.ELEMENT_NODE) {
        let selector = el.nodeName.toLowerCase();
        if (el.id) {
            selector += '#' + el.id;
            path.unshift(selector);
            break;
        } else {
            let sib = el, nth = 1;
            while (sib = sib.previousElementSibling) {
                if (sib.nodeName.toLowerCase() == selector)
                    nth++;
            }
            if (nth != 1)
                selector += ":nth-of-type("+nth+")";
        }
        path.unshift(selector);
        el = el.parentNode;
    }
    return path.join(" > ");
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容