简体   繁体   English

不能将DOM节点的属性用作XPath / CSS选择器查询的过滤器

[英]Can't use DOM Node's properties as filters on XPath / CSS Selector query

I'm trying to search DOM elements using DOM Node's properties , like innerText and textContent , as filters, but without success. 我正在尝试使用DOM Node的属性 (例如innerTexttextContent )作为过滤器来搜索DOM元素,但没有成功。

Take this HTML for instance: 以以下HTML为例:

<html>
  <body>
    <div class="one">
      <div class="two">
        <div class="three">
          <div>Text Here</div>
        </div>
      </div>
    </div>
  </body>
</html>

If I search for a node using the class attribute I can access the innerText property, both with XPath (evaluate) and CSS Selector (querySelectorAll) functions: 如果我使用class属性搜索节点,则可以使用XPath(评估)和CSS Selector(querySelectorAll)函数访问innerText属性:

document.evaluate("//div[@class = 'one']",
    document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
    null).singleNodeValue.innerText;

document.querySelectorAll("div.one")[0].innerText;

However, using innerText property instead of class gives me no result: 但是,使用innerText属性而不是class不会给我任何结果:

 document.evaluate("//div[@innerText = 'Text Here']",
     document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
     null).singleNodeValue;

 document.querySelectorAll("div[innerText='Text Here']")[0];

I tested with the nodeName and textContent and it failed as well, so this is why I think it is related with this DOM properties which are not tag attributes. 我用nodeNametextContent进行了测试,它也失败了,所以这就是为什么我认为它与不是标签属性的DOM属性有关。

I tried using XPath text() function, but using it on <div class="one"> from the example above won't return "Text Here". 我尝试使用XPath text()函数,但是在上例中的<div class="one">上使用它不会返回“ Text Here”。

All the tests were made on Google Chrome v67, on Linux Mint. 所有测试均在Linux Mint的Google Chrome v67上进行。

Why does this happens? 为什么会这样? Is there any solution or workaround for what I'm trying to do? 我要做什么有解决方案或解决方法?

innerText is not an attribute , so @innerText doesn't work. innerText不是属性 ,因此@innerText不起作用。 Also 'Text Here' is not a child text node of <div class="one"> , but descendant text node, so //div[text()='Text Here' and @class='one'] will not work (however //div[.//text()='Text Here' and @class='one'] should work) 另外, 'Text Here'不是<div class="one">的子文本节点,而是后代文本节点,因此//div[text()='Text Here' and @class='one']将不起作用(但是//div[.//text()='Text Here' and @class='one']应该可以)

You should try below to locate required div by its text content : 您应该在下面尝试按文本内容查找所需的div

document.evaluate("(//div[.='Text Here'])[1]",
     document, null, XPathResult.FIRST_ORDERED_NODE_TYPE,
     null).singleNodeValue;

If there are more descendant text nodes, but you want to locate just by "Text Here" , you can try XPath: 如果有更多的后代文本节点,但是您只想通过"Text Here"进行定位,则可以尝试XPath:

(//div[.//div='Text Here'])[1]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM