Uzair Farooq
Uzair Farooq

Reputation: 2437

jQuery .text('') on multiple nested elements

I wanted to remove all text from html and print only tags. I Ended up writing this:

var html = $('html');
var elements = html.find('*');
elements.text('');
alert(html.html());

It only out prints <head></head><body></body>. Was not that suppose to print all tags. I've nearly 2000 tags in the html.

Upvotes: 0

Views: 1847

Answers (4)

Bergi
Bergi

Reputation: 664980

You just deleted everything from your dom:

$('html').find('*').text('');

This will set the text of all nodes inside the <html> to the empty string, deleting descendant elements - the only two nodes that are left are the two children of the root node, <head></head> and <body></body> with their empty text node children - exactly the result you got.

If you want to remove all text nodes, you should use this:

var html = document.documentElement;
(function recurse(el) {
    for (var i=0; i<el.childNodes.length; i++) {
        var child = el.childNodes[i];
        if (child.nodeType == 3)
            el.removeChild(child);
        else
            recurse(child);
    }
})(html);
alert(html.outerHTML);

Upvotes: 2

Kaizen Programmer
Kaizen Programmer

Reputation: 3818

lonesomeday seems to have the right path, but you could also do some string rebuilding like this:

    var htmlString=$('html').html();
    var emptyHtmlString="";
    var isTag=false;

for (i=0;i<htmlString.length;i++)
{
    if(htmlString[i]=='<')
        isTag=true;
    if(isTag)
    {
        emptyHtmlString+=htmlString[i];
    }
    if(htmlString[i]=='>')
        isTag=false;
}
alert(emptyHtmlString);

Upvotes: 0

Kundan Singh Chouhan
Kundan Singh Chouhan

Reputation: 14302

Try this instead

$(function(){

    var elements = $(document).find("*");

    elements.each(function(index, data){
        console.log(data);
    });

});

This will return all the html elements of page.

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237975

var elements = html.find('*');
elements.text('');

That says "find all elements below html, then empty them". That includes body and head. When they are emptied, there are no other elements on the page, so they are the only ones that appear in html's content.

If you really wnat to remove all text from the page and leave the elements, you'll have to do it with DOM methods:

html.find('*').each(function() {               // loop over all elements
    $(this).contents().each(function() {       // loop through each element's child nodes
        if (this.nodeType === 3) {             // if the node is a text node
            this.parentNode.removeChild(this); // remove it from the document
        }
    });
})

Upvotes: 5

Related Questions