views:

27

answers:

4

Hoping someone can help. I need to grab any text node inside the body. Even if it is NOT contained within any other element.

I've tried:

$("p, div, html, body").each(function(){
    $(this).contents().filter(function() {
        var regExText = /(\w|\d|,|;|&)/;                                           
        if (this.nodeType == 3 && regExText.test(this.nodeValue)) {
            $(this).wrap('<span></span>');
            }
      });
});

This is grabbing them in the Ps and Divs but not in the body itself.

+1  A: 

This is not what you want?

$('body').text();
Thomas
A: 

What you have should work, you can test it here. I'd say there's no need to include html in your selector though, is there really anything outside of the <body> element you want to deal with in a <span>?

Nick Craver
+1  A: 

contents() will only return the children elements of the tags you have specified - p, div, html, and body. A text node inside a td or a h1 tag will not be found for instance.

One way to get all text nodes inside the <body> tag using jQuery is to search for children of body and its descendants,

$("body, body *").contents().filter(function() {
    // if this is a text node and matches regex
    // then do something to it
}

You can find various other non-jQuery approaches to get all text nodes in this answer.

Anurag
A: 

Why don't you just clean the HTML?

var strInputCode=$("body").html();
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
alert("Output text:\n" + strTagStrippedText);  

I must admit that probably $("body").text(), does the thing.

netadictos