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>
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()
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With