如何使用javascript获取元素的CSS选择器? [英] How to get css selector for an element using javascript?

查看:146
本文介绍了如何使用javascript获取元素的CSS选择器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有返回唯一选择特定元素的CSS选择器的jQuery插件或javascript代码?

Is there any jQuery plugin or javascript code that returns a CSS-selector that uniquely selects a particular element?

我正在寻找具有与所提供功能相似的功能通过Chrome开发人员工具中的 Copy CSS Path 函数,为我提供了一个类似于以下内容的选择器:

I'm looking for something with similar functionality as provided by the Copy CSS Path function in Chrome's developer tools, giving me a selector that looks something like this:

#question > table > tbody > tr:nth-child(2) > td > div > h2

我尝试过的答案

在Jquery中获取元素的唯一选择器

获取唯一的选择器jQuery

推荐答案

刚刚找到了这篇文章,看看唯一的答案,就因为它的复杂性和对使用jQuery函数的奇怪拒绝而感到震惊。抱歉批评,但是我真的被这个回调系统惊呆了。在这里,使用易于使用的形式:

Just found this post, had a look at the only answer and got terrified by it's complexity and by bizarre denial from using jQuery functions. Sorry for criticism, but i really i got stunned by this callback system. Here, have it in easy to use form:

function getCSSPath(el) {
    let rendered_path_parts = [];

    $( el ).parents().addBack().each((i, el) => {
        const $el = $( el );
        let current_el_path = $el.prop('tagName').toLowerCase();

        if ($el.attr('id')) {
            current_el_path += '#' + $el.attr('id');
        }

        if ($el.attr('class')) {
            current_el_path += '.' + $el.attr('class').split(' ').join('.');
        }

        rendered_path_parts.push( current_el_path );
    })

    return rendered_path_parts.join(' ');
}

$.fn.extend({
    getPath: function() {
        return getCSSPath(this.length === 1 ? this : this.eq(0));
    }
});

getCSSPath(some_element);
some_jquery_element.getPath();

请注意,呈现的选择器将不包含元素的索引,因此描述性不如选择​​器开发人员工具为你赚。

Note that rendered selector will not include element' index, so it is less descriptive than selector developer tools can make for you.

这篇关于如何使用javascript获取元素的CSS选择器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆