获取选择器的元素路径

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

$('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" 

非常感谢!

也许是这样的:

 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)); }); }); 

反对这个:

   
  • hi
  • hello world

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

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

@ jcern修改版的精彩代码 。

特征:

  • 如果元素具有id:仅显示#elementId
  • 如果没有id:show element.className
  • 如果没有类:show element ,其中附加了innerHtml (如果有的话)
  • 跳过元素以缩短输出
  • 不依赖于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  and  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; } 

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

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

请求有点愚蠢,因为有更好的方法。

为元素分配唯一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; });