为选择器获取元素路径

问题描述 投票:6回答:4

遇到麻烦,基本上试图创建一个可用作选择器的变量。例如

$('a').click(function(){
   var selector = $(this).dompath();
});

HTML:

html
    body
        div
            div /div
        /div
       ul
         li
         li
       /ul
    div
        ul
           li
           li
           li hello world
        /ul
   /div
   body
html

这将返回类似的内容

path = html body div ul li:contains('hello world')

然后我可以在选择器中使用它来选择此div,因此,如果我愿意的话

$(path).text() would return "hello world"

非常感谢!

jquery dom xpath element
4个回答
14
投票

也许像这样:

function dompath( element )
{
    var path = '';
    for ( ; element && element.nodeType == 1; element = element.parentNode )
    {
        var inner = $(element).children().length == 0 ? $(element).text() : '';
        var eleSelector = element.tagName.toLowerCase() + 
           ((inner.length > 0) ? ':contains(\'' + inner + '\')' : '');
        path = ' ' + eleSelector + path;
    }
    return path;
}

这修改了另一个问题的方法,以解决该问题,并且仅当标签没有子标签时,才通过:contains()运算符添加标签的全文内容。

我已经用这种方法测试过:

$(document).ready(function(){
    $('#p').click(function() {
      console.log(dompath(this));
    });
});

反对:

<html>
    <body>
        <div>
            <div> </div>
        </div>
       <ul>
         <li></li>
         <li></li>
       </ul>
       <div>
         <ul>
           <li id="p">hi</li>
           <li></li>
           <li id="p2">hello world</li>
        </ul>
       </div>
   <body>
<html>

单击p的结果,然后输出为:

html body div ul li:contains('hi')


4
投票

@jcern`s fantastic code的修改版。

功能:

  • 如果元素具有ID:仅显示#elementId
  • 如果没有ID:显示element.className
  • 如果不存在任何类,请显示element,并附加innerHtml(如果有)
  • 跳过<body><html>元素以缩短输出
  • 不依赖jQuery
function dompath(element) {
    var path = '',
    i, innerText, tag, selector, classes;

    for (i = 0; element && element.nodeType == 1; element = element.parentNode, i++) {
        innerText = element.childNodes.length === 0 ? element.innerHTML : '';
        tag = element.tagName.toLowerCase();
        classes = element.className;

        // Skip <html> and <body> tags
        if (tag === "html" || tag === "body")
            continue;

        if (element.id !== '') {
            // If element has an ID, use only the ID of the element
            selector = '#' + element.id;

            // To use this with jQuery, return a path once we have an ID
            // as it's no need to look for more parents afterwards.
            //return selector + ' ' + path;
        } else if (classes.length > 0) {
            // If element has classes, use the element tag with the class names appended
            selector = tag + '.' + classes.replace(/ /g , ".");
        } else {
            // If element has neither, print tag with containing text appended (if any)
            selector = tag + ((innerText.length > 0) ? ":contains('" + innerText + "')" : "");
        }

        path = ' ' + selector + path;
    }
    return path;
}

0
投票

您需要枚举要为其创建查询的元素的所有父元素,并为每个父元素添加一个选择器,例如父节点的节点名称或包含包含测试的名称(如果该父节点需要该测试)。如果需要此包含测试,确保的唯一方法可能是在每个步骤中将当前查询应用于当前父对象,并检查查询是否仅返回目标元素。然后添加包含测试,如果它匹配太多...

我写了一个Greasemonkey script。首先,它收集在另一棵树(“模板”)中找到目标元素所需的所有元素,然后将其转换为查询。但是,如果属性不够独特,它将使用属性(特别是class / id / name)而不是文本进行匹配,并且使用位置(如果属性不够独特),因为我认为大多数情况下文本的更改要比结构更改的频繁。


0
投票

请求有点愚蠢,因为有一种[[much更好的方法。

或者为元素分配一个唯一的ID以在以后快速引用它,或者如果已经分配了ID,则使用它。

// // generate a unique (enough) id for an element if necessary // function getUID(id) { if(window["uidCounter"]==null) window["uidCounter"]=0; return id||( (window["uidCounter"]++) + "_" + (new Date()).getTime() ); } // // use an #ID selector // $('a').click(function(){ var uid = getUID( $(this).attr('id') ); $(this).attr('id', uid); var selector = "#" + uid; });

© www.soinside.com 2019 - 2024. All rights reserved.