How to extract the text between <a></a>
Question
I must use jQuery for first time....
<a class="Tag Resource" href="http://localhost/"
resource="http://localres/" property="prop">test</a>
I've tried to extract the text using var = $('a').find('Tag Resource').text();
and var = $('a').find('Tag Resource').html();
but it doesn't work. I need "test" as plain text.
Can someone tell me how to do this?
Thanks in advance
Solution
I think you're looking for:
var t = $("a.Tag.Resource").text();
meaning a tags that have both the Tag
and Resource
classes. The find() method is for searching subtrees of elements.
OTHER TIPS
Here you go (live demo):
$(document).ready(
function (){
alert( $('a.Tag.Resource').html() );
});
Your issue is either that you wanted one class but used a space so it became two; or that when referring to classes with a jquery selector, you need to prefix them with a period.
In any case, the above code will help. If you really just wanted one class, change it to $('a.Tag-Resource')...
I think the problem is the syntax of your find expression.
Update: In fact, you don't want find at all, you want filter. Find will only select descendants of the a elements, rather than the elements themselves.
I've tested the example line below.
From the example here, it looks like you want
var text = $('a').filter('.Tag.Resource').text();
var text = "";
$("a").each(function(){
text += $(this).html() + " " + $(this).attr("resource");
});
alert(text);
I don't think you can have class names with spaces in. You've added 2 classes "Tag" and"Resource" to the a tag and your find selectory won't find that.
Remember, class names can be repeated on a page, and spaces indicate two classes applied to an element. You are not guaranteed that a single element will have that class, so .text() may return the combined text of all matched elements.
$(".Tag.Resource").text();
Well, you don't have to use JQuery...
var text, links = document.links;
for (var i = 0; i < links.length; i++) {
if (links[i].className == 'Tag Resource') {
text = links[i].innerText;
break;
}
}
alert(text);