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