4

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.

3 Answers 3

5

Use the nodeValue property:

$("#yourInputField").val(yourTextNode.nodeValue);
Sign up to request clarification or add additional context in comments.

1 Comment

This is the correct answer to my question. I liked the spin thg435 gave. Thanks!
3

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()

http://jsfiddle.net/YXjEB/

Comments

3

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.

1 Comment

textContent is not implemented in older browsers, including IE < 9. Stick with nodeValue or data, both of which are available in all major browsers.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.