How to find a link in a page based on its href attribute?
I am trying to find the first link of my page which url fit to "AAA"
(example).
I first try to get the links with this href:
$('a[href$="AAA"]')
Then selec the first one:
$('a[href$="AAA"]')[0]
Then target the title attribute of this 开发者_高级运维link
$('a[href$="AAA"]')[0].attr("title");
But all of this return me "undefined", at each step. How to do that?
Example anchor:
<a href="contents/medias/images/news/news_test_big.jpg" title="Nouvelle réalisation en ligne 1 FR" target="_blank" class="imageLink">
How about:
$("a[href='AAA']").first().attr("title")
// or
$("a[href='AAA']:first").attr("title")
Then it depends if you want the href to be equal to 'AAA', contains it, starts/ends with it. In that case you wouldn't use href=
but href$=
for instance. Neil's answer contains the different types of tests you can use.
If you could post your HTML code it would help as well.
$('a[href$="AAA"]')
should work fine, but it searches for href
s that end with AAA.
Try:
$('a[href="AAA"]')
- Equals AAA
Or:
$('a[href*="AAA"]')
- Contains AAA
Assuming that you have a matching link (i.e., one that ends with AAA).
$('a[href="AAA"]:first').attr('title');
should work.
The reason that you are getting undefined for attr
is that it isn't a jQuery object after you apply the indexer to the result of the query, it's the actual DOM element. To use attr
, it needs to still be a jQuery object. Using the :first
selector will reduce the results of the query to the first matching one. Since attr
will return the value of the first matching attribute, it's not strictly necessary, but I think it makes the intent clearer. If you go to set the attribute value, attr
will apply to all of the matching elements so, in that case, it's important -- thus I would use it in both places for clarity.
The way you've written it, you're looking for an href that ends with "AAA". Is that your intent?
$=
means "ends with"^=
means "starts with"~=
means "contains"
References: jQuery Selectors
精彩评论