I would like to get all descendant text nodes of an element, as a jQuery collection. What is the best way to do that?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
Jauco posted a good solution in a comment, so I'm copying it here:
For some reason
contents()
didn't work for me, so if it didn't work for you, here's a solution I made, I createdjQuery.fn.descendants
with the option to include text nodes or notUsage
Get all descendants including text nodes and element nodes
Get all descendants returning only text nodes
Get all descendants returning only element nodes
Coffeescript Original:
Drop In Javascript Version
This is cross browser, a small
Array.indexOf
polyfill is included in the code.jQuery.contents()
can be used withjQuery.filter
to find all child text nodes. With a little twist, you can find grandchildren text nodes as well. No recursion required:jsFiddle
jQuery doesn't have a convenient function for this. You need to combine
contents()
, which will give just child nodes but includes text nodes, withfind()
, which gives all descendant elements but no text nodes. Here's what I've come up with:Note: If you're using jQuery 1.7 or earlier, the code above will not work. To fix this, replace
addBack()
withandSelf()
.andSelf()
is deprecated in favour ofaddBack()
from 1.8 onwards.This is somewhat inefficient compared to pure DOM methods and has to include an ugly workaround for jQuery's overloading of its
contents()
function (thanks to @rabidsnail in the comments for pointing that out), so here is non-jQuery solution using a simple recursive function. TheincludeWhitespaceNodes
parameter controls whether or not whitespace text nodes are included in the output (in jQuery they are automatically filtered out).Update: Fixed bug when includeWhitespaceNodes is falsy.
Can also be done like this:
The above code filters the textNodes from direct children child nodes of a given element.