当前位置: 动力学知识库 > 问答 > 编程问答 >

Grab any Text Node within the BODY using Jquery

问题描述:

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.

网友答案:

This is not what you want?

$('body').text();
网友答案:

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.

网友答案:

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>?

网友答案:

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.

分享给朋友:
您可能感兴趣的文章:
随机阅读: