3

How would I return Some Text, <a href="abc.html">Some Anchor</a>, and <img src="abc.jpg" /> from the following three elements without using jQuery? In other words, how would I return $('#t1).text(), $('#t2).text(), $('#t3).text() without using jQuery? I don't need to return an array if multiple elements as I will only select one element at a time.

<td id="t1">Some Text</td>
<td id="t2"><a href="abc.html">Some Anchor</a></td>
<td id="t3"><img src="abc.jpg" /><td>

jQuery does text() as follows. It seems overkill since I am not worried about returning an array for multiple elements.

text: function( value ) {
    return jQuery.access( this, function( value ) {
        return value === undefined ?
            jQuery.text( this ) :
            this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
    }, null, value, arguments.length );
},

Thanks

6
  • 1
    $('#t2') would return Some Anchor, not <a href.... Same for $('#t3'). Commented Nov 16, 2012 at 16:12
  • Can you just read the innerHTML property after using document.getElementById()? Commented Nov 16, 2012 at 16:13
  • @CrazyJugglerDrummer. No, it will only work for the <a> and <img>, not the text node. Commented Nov 16, 2012 at 16:14
  • do you need to handle this case <a>a <b>b</b> c</a> and retrieve a b c? Commented Nov 16, 2012 at 16:15
  • @FlorianMargaine. You are right. I guess it would be equivalent to .html(). Commented Nov 16, 2012 at 16:17

2 Answers 2

6

You can retrieve the text of a node(s) like so:

var el = document.getElementById("t1");
var text = el.textContent || el.innerText;

Some more info on textContent and innerText on the MDN site here

Sign up to request clarification or add additional context in comments.

2 Comments

Ah ha!, Thanks! I first was using el.data, and it worked without the html elements. Later tried innerHTML, and it erred on the text values. Just curious, why textContent over data, and innerText over innerHTML?
@user1032531 innerText is IE's version of textContent. One thing to watch out with innerText is that it won't return hidden text. For more info look at the link to MDN. They explain it much better then I ever could :)
2

data is a property on Nodes to get its data (non recursive). innerHTML is the HTML, a property on Elements. textContent is the standard property to get the text (without HTML) of an Element. innerText is the non-standard old-IE way to get textContent.

You now should know what you need :-)

1 Comment

Thanks Florian, Now I know more!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.