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

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

问题描述


使用javascript或jquery(当我选择/悬停在对象上时)。 b

我不提前知道结构。



例如:

 < HTML> 
< body>
< div>
< div>
未选择
< / div>
< div>
所选文本
< / div>
< / div>
< / body>
< / html>

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

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

任何帮助将不胜感激。



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



顺便说一句,这个路径有一个技术的名称?

我看过XPath这个词,但不能肯定是这样的。



快乐,享受生活。

解决方案

以下函数使用jQuery:

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

您可以这样使用:

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

您可以测试它 here


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天全站免登陆