Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>jQuery doesn't have a convenient function for this. You need to combine <code>contents()</code>, which will give just child nodes but includes text nodes, with <code>find()</code>, which gives all descendant elements but no text nodes. Here's what I've come up with:</p> <pre><code>var getTextNodesIn = function(el) { return $(el).find(":not(iframe)").addBack().contents().filter(function() { return this.nodeType == 3; }); }; getTextNodesIn(el); </code></pre> <p><strong>Note: If you're using jQuery 1.7 or earlier, the code above will not work. To fix this, replace <a href="http://api.jquery.com/addBack/" rel="noreferrer"><code>addBack()</code></a> with <a href="http://api.jquery.com/andSelf/" rel="noreferrer"><code>andSelf()</code></a>. <code>andSelf()</code> is deprecated in favour of <code>addBack()</code> from 1.8 onwards.</strong></p> <p>This is somewhat inefficient compared to pure DOM methods and has to include an <a href="http://bugs.jquery.com/ticket/11275" rel="noreferrer">ugly workaround for jQuery's overloading of its <code>contents()</code> function</a> (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function. The <code>includeWhitespaceNodes</code> parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).</p> <p>Update: Fixed bug when includeWhitespaceNodes is falsy.</p> <pre><code>function getTextNodesIn(node, includeWhitespaceNodes) { var textNodes = [], nonWhitespaceMatcher = /\S/; function getTextNodes(node) { if (node.nodeType == 3) { if (includeWhitespaceNodes || nonWhitespaceMatcher.test(node.nodeValue)) { textNodes.push(node); } } else { for (var i = 0, len = node.childNodes.length; i &lt; len; ++i) { getTextNodes(node.childNodes[i]); } } } getTextNodes(node); return textNodes; } getTextNodesIn(el); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload