简体   繁体   中英

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.

Take this HTML for instance:

<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:

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:

 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.

I tried using XPath text() function, but using it on <div class="one"> from the example above won't return "Text Here".

All the tests were made on Google Chrome v67, on Linux Mint.

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. 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)

You should try below to locate required div by its text content :

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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