0

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.

Josh Darnell
  • 11,304
  • 9
  • 38
  • 66

4 Answers4

1

This is not what you want?

$('body').text();
Thomas
  • 2,162
  • 1
  • 13
  • 10
1

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.

Community
  • 1
  • 1
Anurag
  • 140,337
  • 36
  • 221
  • 257
0

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
  • 623,446
  • 136
  • 1,297
  • 1,155
0

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
  • 7,602
  • 2
  • 42
  • 69