Friday, April 29, 2011

Using jQuery, how do I get the text value of an element?

Hi,

how do I retrieve the text between the href tag?

<a href="blah">GET THIS TEXT</a>

It is wrapped in this DOM:

<div class="c1">
   <div class="c2"><a href="#">GET THIS TEXT</a>
   </div>
</div>
From stackoverflow
  • You are looking for the text() property:

    $('a', 'div.c2').text();
    

    The reason div.c2 is defined as the second argument is because it would then be the context of the selector. By default jQuery searches the entire document when you use $(), by specifying div.c2 it is only going to search inside of <div>'s with a class of c2.

    Keeping this in mind, you could also rewrite the above like this:

    $('div.c2 a').text();
    

    Most people prefer this because it is the syntax that you would use to select this element in a CSS stylesheet. However, jQuery then has to figure that out. You could even do:

    $('div.c2').find('a').text();
    

    However, I prefer the context method as I feel it is cleaner and marginally faster, not that it matters.

    There is also the html() property, which gets the contents, including HTML.

    So if your link was like this:

    <a href='#'><b>Hi There</b></a>
    

    Then:

    $('a').text(); // would return Hi There
    $('a').html(); // would return <b>Hi There</b>
    
    altCognito : Note that you can write that also as $('div.c2 a').text(); It's not necessary to split it off into another function.
    Paolo Bergantino : I know, but I very much prefer to help out jQuery do the parsing. I think it's cleaner to specify a context whenever possible than to just have a selector string.
    Paolo Bergantino : I updated my answer to note your comment, alt.
  • I think that .text() or .html() will work, depending on whether you don't or do want any markup that appears inside the tag.

    var txt = $('div.c2 > a').text();
    
    var html = $('div.c2 > a').html()
    

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.