Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find ANY text without tags

Tags:

jquery

I have some text without tags. I try to find it. With jQuery

(this is dinamic text, so I do not know how many peaces of text I have or where they are. I just know that are inside a div. This is different from other questions around)

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

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

In fiddle if you like 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>

SOLUTION EXPECTED: So I would like to find the text without tags and wrap it in a p tag. In the 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>
like image 938
Nrc Avatar asked Feb 22 '15 11:02

Nrc


2 Answers

One solution to avoid wrap and white spaces is to use trim like:

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

fiddle

References

Node.nodeValue

String.prototype.trim()

like image 73
Alex Char Avatar answered Nov 14 '22 00:11

Alex Char


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

This will filter out those text nodes which are only spaces, tabs, or newlines.

Here is the fork of your fiddle and the respective snippet 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>
like image 37
Shef Avatar answered Nov 14 '22 02:11

Shef