Dom
Dom

Reputation: 7315

Jquery backwards tree traversal

I'm looking for a solution to a little problem I have, currently I'm looking to get the entire DOM tree from an element (e.g. all the parents), which I can do using .closest('body').first().

The problem is I'm looking for a way to go through each element and parent and remove all of the text/html from them except the original target, so basically have a blank tree but have html in the bottom element.

Although I haven't tried it yet, I was thinking just .each() might work, although something tells me it would have a problem with the nested structure?

Any advice would be great!

Thanks Dom

UPDATE: Accepted answer works great! I adapted the code and added to the fiddle below to allow it to work with deep nested structures like the ones I was working with...

Fiddle here: http://jsfiddle.net/RDNTc/2/

Upvotes: 1

Views: 97

Answers (2)

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

That script remove every text nodes of the parent of the target :

$('p').parentsUntil('body').each(function(){
    $(this).contents().each(function(){
        if(this.nodeType === 3) this.parentNode.removeChild(this);
    });
});

http://jsfiddle.net/RDNTc/;

Upvotes: 2

Ahmed
Ahmed

Reputation: 656

You can traverse up the parents in jQuery using .parents(). Then use .each() to iterate over them in a loop.

Upvotes: 0

Related Questions