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.
精彩评论