选定元素的 html dom 中的路径是什么? [英] What is the path in the html dom for a selected element?

查看:22
本文介绍了选定元素的 html dom 中的路径是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取特定对象的 html dom 中的路径.
使用 javascript 或 jquery.(当我选择/悬停在对象上时.)

我事先不知道结构.

例如:

<身体><div><div>未选中的

<div>所选文字

选定文本"Div 路径应该类似于:

//HTML/BODY/DIV[0]/DIV[1]

任何帮助将不胜感激.

我已经看过这个答案但是它没有给出有关元素索引的指示(在我的示例中,方括号中的值 - DIV[1] 中的 1).

顺便说一下,这条路径有技术"名称吗?
我见过 XPath 这个词,但不确定是不是这个.

快乐,享受生活.

解决方案

以下函数使用 jQuery 执行您想要的操作:

function getElementPath(element){return "//" + $(element).parents().andSelf().map(function() {var $this = $(this);var tagName = this.nodeName;如果 ($this.siblings(tagName).length > 0) {tagName += "[" + $this.prevAll(tagName).length + "]";}返回标签名称;}).get().join("/").toUpperCase();}

你可以这样使用它:

$(document).ready(function() {$("div").click(function(event) {event.stopPropagation();window.alert(getElementPath(this));});});

您可以在此处进行测试.

I am trying to get the path in the html dom for a specific object.
Using javascript or jquery.(When I select/hover over the object.)

I do not know the structure in advance.

For example:

<html>
    <body>
        <div>
            <div>
                Not selected
            </div>
            <div>
                Selected Text
            </div>
        </div>
    </body>
</html>

The "Selected Text" Div path should be something like:

//HTML/BODY/DIV[0]/DIV[1]

Any help will be appreciated.

I have looked at this answer but it does not give an indication regarding the index of the element (In my example the value in the square brackets - 1 in DIV[1]).

By the way is there a "technical" name for this path?
I have seen the term XPath but am not sure that this is it.

Be happy and enjoy life.

解决方案

The following function does what you want, using jQuery:

function getElementPath(element)
{
    return "//" + $(element).parents().andSelf().map(function() {
        var $this = $(this);
        var tagName = this.nodeName;
        if ($this.siblings(tagName).length > 0) {
            tagName += "[" + $this.prevAll(tagName).length + "]";
        }
        return tagName;
    }).get().join("/").toUpperCase();
}

You can use it like this:

$(document).ready(function() {
    $("div").click(function(event) {
        event.stopPropagation();
        window.alert(getElementPath(this));
    });
});

You can test it here.

这篇关于选定元素的 html dom 中的路径是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆