JQuery text Node Object in a string

I am 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 ); 

He used to capture text nodes from html

For instance:

 <div> <span>Testing</span> What is this? </div> 

I'm looking for What is this?

This works as I can do console.log and see the result in the console.

But when I try to use the result in the input field, it gives me: [object Text]

How can I use the result as a string value?

I tried toString (), but this gives the same result if I did not miss anything.

+4
source share
3 answers

Your code works, but it does not use the beauty of jQuery. What about:

 (function($) { $.expr[':'].textnode = function(element) { return element.nodeType == 3; } $.valHooks["#text"] = { get: function(elem) { return $.trim(elem.nodeValue); }} })(jQuery) 

use it as follows:

 lastText = $("div").contents(":textnode:last").val() 

http://jsfiddle.net/YXjEB/

+2
source

Use the nodeValue property:

 $("#yourInputField").val(yourTextNode.nodeValue); 
+5
source

You get the text node as a DOM object, which is the correct behavior when you need the actual use of the text: textContent or nodeValue .

See jsFiddle .

+2
source

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


All Articles