Reputation: 8182
I'm using this code:
/**
* Get Text Nodes from an Element
* Returns and object unless number is passed in
* Numbers is 0 based
*/
(function( $ ) {
$.fn.textNodes = function(number) {
var nodes = jQuery(this).contents().filter(function(){
return this.nodeType == 3;
});
if(jQuery.isNumber(number)){
return nodes[number];
}
return nodes;
};
})( jQuery );
It's used to grab the text nodes out of html
For example:
<div>
<span>Testing</span>
What is this?
</div>
I'm looking for What is this?
This works, as I can do a console.log and see the result in the console.
But when I try and use the result in an input field it give me: [object Text]
How can I use the result as a string value?
I've tried toString() but that gives the same result, unless I missed something.
Upvotes: 4
Views: 6385
Reputation: 214959
Your code works, but it doesn't employ the beauty of jQuery. How about:
(function($) {
$.expr[':'].textnode = function(element) {
return element.nodeType == 3;
}
$.valHooks["#text"] = { get: function(elem) {
return $.trim(elem.nodeValue);
}}
})(jQuery)
use it this way:
lastText = $("div").contents(":textnode:last").val()
Upvotes: 3
Reputation: 1176
You receive the text node as a DOM-object which is correct behaviour, when you need the actual text use: textContent
or nodeValue
.
See jsFiddle.
Upvotes: 3
Reputation: 262979
Use the nodeValue property:
$("#yourInputField").val(yourTextNode.nodeValue);
Upvotes: 5