views:

152

answers:

2

Suppose I have this:

<ul id="menu">
<li><a href="someplace">some text</a><li>
...
</ul>

I want to make every li clickable so I need to extract the value of href like this:

$('#menu li').click(function() {
    var link_to = $(SELECTOR THAT I NEED).attr('href');
    window.location = link_to;
});

what's the correct code for this? Is there a better way?

+3  A: 
$('#menu li').click(function() {
    var link_to = $(this).children("a").eq(0).attr('href');
    window.location = link_to;
});
mck89
I'd personally prefer `$(this).children("a:first").attr("href")`
Garry Shutler
`$('a:first', this)` would be a neat way to avoid having to run the clicked `li` through the `$` function. providing context in this manner is exactly the same as `find`. i've already cast my vote for the don't-do-what-you're-trying-to-do alternative, but i think this post, and its comments, is a valid documentation for those who stumble upon this question, having a *similar* question of their own, where Gaby's reply is not applicable =)
David Hedlund
+2  A: 

Since you have a link in there, why not use that ?

you could set it to display:block with css if you want it to take up the whole li width ..

#menu li a{display:block;}

and avoid using jquery for built in functionality .. (if i understand correctly..)

Gaby
Good point, haven't thought of `display: block`. It's not ideal though because the padding of the `li` elements is outside the `a` block and so is "dead".
kemp
Yes you are right .. but it was worth a shot without knowing exactly what you are after :) The asnwers above should do it then ..
Gaby
i'll vote this one up and remove my own post. it is clearly redundant to have a lot of click bindings when the anchor semantically handles onclicks. i'd say it's definitely worth the css-effort to remove the padding that the li's create.
David Hedlund
I agree, accepting this as it answers the "is there a better way" part of my question. The other answers were good too, yours David was the most concise version
kemp