I have a nested set of html tags and I want to remove all tags and their children without text.
Example:
<div id="mydiv"> <span></span> <span><br></span> <span> <span><br></span> </span> <span> <span><br> <span></span> </span> </span> <span> <img src="someimg.jpg" width="100" height="100"> </span> <span>some text</span> </div>β
So, I want the gaps with images and text to remain, while others to go.
I need this result after my function :
<div id="mydiv"> <span> <img src="someimg.jpg" width="100" height="100" /> </span> <span>some text</span> </div>β
I realized this had to be done recursively with either JavaScript or jQuery with its .children () method, here is my code that I wanted to use, but I cannot figure out how to build recursion:
var remove_filter = function () { children= $(this).children(); for (var i = -1, l = children.length; ++i < l;) { if ($(children[i]).text() == "") { $(children[i]).remove(); }
This code is broken, it removes and leaves empty spaces ... How do I get the result with recursion?
EDITED
Here is my jsfiddle: http://jsfiddle.net/EGVQH/
EDITED 2 times
I found a mistake in the correct answer, but it is small. If I have a code like this:
<div id="mydiv"> <span> <br> Some text</span> <span> <span><br> <span></span> </span> </span> <span> <img src="someimg.jpg" width="100" height="100"> </span> <span>some text</span> </div>β
I assume this will result in:
<div id="mydiv"> <span> Some text</span> <span> <img src="someimg.jpg" width="100" height="100" /> </span> <span>some text</span> </div>β
the previous βRightβ answer to my question gave the wrong result in <span> <br> Some text</span> . Other answers were incorrect after testing a bit.
See my JSfiddle: http://jsfiddle.net/EGVQH/2/
javascript jquery recursion
Feanor
source share