I was looking for an answer to this question, and I came up with this
stackoverflow - How do I select text nodes with jQuery?
Is there so far another way to do this ?? In my very case I'm trying to find every text node starting from a given DOM element and
empty()
it. Any suggestions ?
UPDATE - After a bit of messing I came up with this jsFiddle
Now the function selects each text node but instead of replacing only the empty ones with the new value given, it replaces all of them. What am I doing wrong ??
Text nodes are a type of node that denotes the actual text inside an element. The textNodes of any element can be selected using jQuery by selecting all the nodes and using the filter() method to check the nodeType property. The required element is first selected using the jQuery selector.
Remove a Text Node Set the variable x to be the first title element node. Set the variable y to be the text node to remove. Remove the element node by using the removeChild() method from the parent node.
A text node encapsulates XML character content. A text node can have zero or one parent. The content of a text node can be empty. However, unless the parent of a text node is empty, the content of the text node cannot be an empty string.
With reference to this 'Now the function selects each text node but instead of replacing only the empty ones with the new value given, it replaces all of them. What am I doing wrong ??'
What is required is that just test the nodeValue for whitespace using a regex and then on the basis of this proceed forward.
I have updated it like this and it works fine http://jsfiddle.net/Vj5LR/2/
$(document).ready(function(){
var prova = ['1','2','3','4','5','6'];
var regForNonWhiteSpace = /\S/; // non white space
$('.example').find('*').each(function(){
$(this).contents().filter(function(){
//this.trim();
if( this.nodeType === 3 && !regForNonWhiteSpace.test(this.nodeValue)){
this.nodeValue = 'new value'; // only when there is no content at all
}
});
});
});
Hope this solves the problem
empty()
is used to empty the innerText
of an element and does not apply to textNodes. Instead you need to use remove()
:
$('.example')
.contents()
.filter(function () {
return this.nodeType === 3; //Node.TEXT_NODE
}).remove();
Example fiddle
$(document).ready(function(){
var prova = ['1','2','3','4','5','6'];
$('.example').find('*').each(function(){
$(this).contents().filter(function(){
//this.trim();
if( this.nodeType === 3 && this.nodeValue.trim().length === 0){
this.nodeValue = 'new value';
}
});
});
});
http://jsfiddle.net/trevordowdle/RajB4/40/
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