Select "Text" node using querySelector

It can't, though my answer isn't that authoritative. ( You may have figure it out)

You can check out this select text node with CSS or Is there a CSS selector for text nodes.

Some verbose explaination(maybe useless, English is not my first language, sorry for some misusing of words or grammar.):

I was learning about ParentNode and since the querySelectorAll() method returning a NodeList, I was wondering if it could select text node. I tried but failed; googled and found this post.

Argument in querySelectorAll(selectors) or querySelector(selectors) is a DOMString containing one or more CSS selectors (of course no containing pseudo-element, otherwise the method would return null) which only apply to elements (not plain text).


As already answered, CSS does not provide text node selectors and thus document.querySelector doesn't.

However, JavaScript does provide an XPath-parser by the method document.evaluate which features many more selectors, axises and operators, e.g. text nodes as well.

let result = document.evaluate(
  '//div[@class="a"]/div[@class="clear"]/following-sibling::text()[1]',
  document,
  null,
  XPathResult.STRING_TYPE
).stringValue;

console.log(result.trim());
<body>
  <div class="a">
    <h1>some random text</h1>
    <div class="clear"></div>
    Extract This Text
    <p></p>
    But Not This Text
    <h2></h2>
  </div>
</body>

// means any number of ancestor nodes.
/html/body/div[@class="a"] would address the node absolutely.

It should be mentioned that CSS queries work much more performant than the very powerful XPath evaluation. Therefore, avoid the excessive usage of document.evaluate when document.querySelectorAll works as well. Reserve it for the cases where you really need to parse the DOM by complex expressions.