views:

99

answers:

1

I am trying to find some child a elements within a ul parent. But, I need to only find the first a. Here is what I am using

$('div.item a').click(function() {
    $(this).parent().next('ul.subItems').find('a:first').addClass('selected');
});

HTML:

<div class="item"><a id="main5830" href="http://www.mysite.com"&gt;Test&lt;/a&gt;&lt;/div&gt;
<ul class="subItems">
<li><a>test 1</a></li>
<li><a>test 2</a></li>
<li><a>test 3</a></li>
</ul>

I would like test 1's a element to get the class of selected.

For some reason, this is not selecting the first a within in the UL, or ANYTHING in the UL element. Have I done something wrong here?

+4  A: 

It does work, just need to use return false; (or event.preventDefault();) at the end of the click event handler to prevent the anchor default click behaviour.

$('div.item a').click(function() {
    $(this).parent().next('ul.subItems').find('a:first').addClass('selected');
    return false;
});

or

$('div.item a').click(function(e) {
    e.preventDefault();
    $(this).parent().next('ul.subItems').find('a:first').addClass('selected');
});

Here's a Working Demo showing it working

Russ Cam
Yeah, am using return false; at the end of my click function, I just didn't include all the code. Hmmm, strange that your demo is working but mine is not...I will look at it again.
Nic Hubbard
perhaps a problem with the code that you haven't posted? If there were to be an error in that code then the code that you have posted may not work in some browsers
Russ Cam