1

Is there a way in jQuery to get all descendant nodes of a parent node, including text nodes, recursively? I know the $.contents() method, but as the jQuery documentation states:

the .contents() method allows us to search through the immediate children of these elements in the DOM tree

My problem is, that I have a child node that contains more (non-text) nodes, and I need instead of just the parent. I am trying some workaround now:

var contents = container.contents();
var foo = $('.foo');
var index = contents.index(foo);
contents.splice(index,1,$('.foo').contents());

...but this inserts the array instead of the individual elements. My final step would be pushing the elements to the contents array one by bone, but I'd like to know if there is a better way to do this.

Sleeper9
  • 1,707
  • 1
  • 19
  • 26

1 Answers1

2

I don't really understand what you are trying to do but in order to get all descendant nodes of a certain element you may use the following:

var nodes = $('*', container).addBack().contents();

DEMO: http://jsfiddle.net/5vfBg/

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • I forgot to mention that I use jQuery 1.7, so I don't have the `addBack()` function. Besides, this is what I would like to achieve (based on the jsfiddle) – Sleeper9 Jun 03 '14 at 14:10
  • @Sleeper9 Then you should use good old `andSelf()` instead: http://jsfiddle.net/5vfBg/1/. – VisioN Jun 03 '14 at 14:11
  • Yes, got it working now, exactly what I wanted. Thanks! – Sleeper9 Jun 03 '14 at 14:13