tags:

views:

58

answers:

2

I have an unordered list such as:

<ul id="cities">
  <li><a href="/london/">London<a></li>
  <li><a href="/new-york/">New York<a></li>
  <li><a href="/paris/">Paris<a></li>
<ul>

using jquery how do i get the href value for "New York"? Only the anchor text value is known through the client so i would like to find the matching anchor text and extract the href.

Thanks

+4  A: 

You can use the :contains selector, like this:

$("#cities li a:contains(New York)").attr('href');

Or more longer, but more accurate (since :contains() would match "New York City" as well), you can use the .filter() method for an exact match, like this:

$("#cities li a").filter(function() {
  return $(this).text() === "New York";
}).attr('href');
Nick Craver
@Akk - Are you running it on `document.ready`, wrapped inside a `$(function() { });` for example? Like this: http://jsfiddle.net/yadpJ/
Nick Craver
A: 
var href = $('ul#cities li a').filter(function() {
  return $(this).text() === "New York";
}).attr('href');
Pointy
When using Id's you don't need to prefix with the element ...
James Westgate
@James - That's *usually* true, but not 100% of the time, one script may be used on a dozen pages, what if `#cities` was a div listing cities, completely unrelated on another page? It *can* matter is the point :) Don't get me wrong though, if you're 100% certain of the ID usage then by all means leave it off, it is a faster selector.
Nick Craver
@James yes, as Nick says it's something I do as a sanity check, and I do it in examples here because it helps clarify. One never knows how accurate are the snippets of sample code in questions here!
Pointy
ul#cities is slower than #cities, since #cities will use the native document.getElementById() method.
David
@David - So will `ui#cities` :) It just does an additional check afterwards, you can see the sizzle source here: http://github.com/jeresig/sizzle/blob/master/sizzle.js
Nick Craver
@David I was under the (mis)impression that Sizzle would check the node *after* fetching by "id" value, but looking at the (dense) code I think you're probably right. When it "chunks" the selector it subsequently only treats pieces that *start* with "#" as "ID" selectors. Good to know! Thanks. (edit - ok Nick I'll look it over again; that code is worth studying as an exercise in any case!)
Pointy
Ah OK, @Nick, that "Expr.matches.ID" pattern **will** match "tagname#id" ...
Pointy
Wow. This generated some comments :D. I meant to say from a performance point of view (and if there is no other reason such as multiple ids)
James Westgate