Find any text without tags

I have text without tags. I'm trying to find him. Using jQuery

(this is dynamic text, so I don’t know how many lines of text I have or where they are. I just know what is inside the div. This is different from other questions)

I could find a solution to search for text without tags, wrap it in <p> But it also spawns some empty tags. So the questions are:
- This.nodeType === 3 It seems to find text and spaces. Can someone explain?
- Can someone solve this problem or show another way to search only text without tags?

(I could find nodeType === 3 "Represents text content in an element or attribute")

In the fiddle, if you want to play there: http://jsfiddle.net/bhpaf8hu/

 $("#tot").click(function() { $("div").contents().filter(function() { return this.nodeType === 3; }).wrap("<p>"); }); 
 p { background:green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="tot"> <h1> This is a h1</h1> Text without p <br> Another text without p <br> <p>This text has p</p> </div> 

DECISION EXPECTED: So I would like to find text without tags and wrap it in p tag. In this example, this is what I am looking for:

 <div id="tot"> <h1> This is a h1</h1> <p>Text without p</p> <br> <p>Another text without p</p> <br> <p>This text has p</p> </div> 
+5
source share
2 answers

One way to avoid wrapping and spaces is to use trim as:

 $("#tot") .contents() .filter(function () { // get only the text nodes return this.nodeType === 3 && this.nodeValue.trim() !== ""; }).wrap("<p />"); 

violin

References

Node.nodeValue

String.prototype.trim ()

+5
source

You can use $.trim() to remove all new lines, spaces (including non-breaking spaces) and tabs from the beginning and end of lines of text nodes.

This will filter those text nodes that are just spaces, tabs or newlines.

Here is the fork of your violin and the corresponding fragment below.

 $("#tot").click(function() { $("div").contents().filter(function() { return this.nodeType === 3 && $.trim($(this).text()) != ''; }).wrap("<p>"); }); 
 p { background:green; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <div id="tot"> <h1> This is a h1</h1> Text without p <br> Another text without p <br> <p>This text has p</p> </div> 
+2
source

Source: https://habr.com/ru/post/1213902/


All Articles