susanloek
susanloek

Reputation: 411

jQuery select first item

I'm using this simple jQuery to prevent the link-redirect:

$("#main-nav .menu-wrapper .menu li.has-sub").find( "a" ).click(function() {
    return false;
});

This is my HTML:

<div id="main-nav">
    <div class="menu-wrapper">
        <ul class="menu">
            <!-- ONLY SELECT THIS LINK -->
            <li><a href="#">Lorem Ipsum</a></li>
            <li class="has-sub"><a href="#">Dolor Sit</a>
                <ul class="sub">
                    <!-- DO NOT SELECT THIS LINK -->
                    <li><a href="#">Lorem Ipsum</a></li>
                </ul>
            </li>
        </ul>
    </div>
</div>

I only want to prevent the redirect of the first Link not of the second (.sub) link. My current script prevents the redirect of all links in my nav!

Upvotes: 0

Views: 628

Answers (5)

Mojtaba
Mojtaba

Reputation: 5004

If you want to select all first level <a> tags, you can use .children instead of .find

If you want to select exactly the first <a> tag, you can use .find('a:first')

By the way, I recommend you do not return false which could stop other possible event listeners and processes too. use event.preventDefault(); instead

$("#main-nav .menu-wrapper .menu li.has-sub").find( "a:first" ).click(function(event) {
    event.preventDefault();
});

Upvotes: 1

strah
strah

Reputation: 6722

In your case, you have only one <a> in the first level of children. So, you could use children() instead of find(), like this:

$("#main-nav .menu-wrapper .menu li.has-sub").children("a").click(function() {
    return false;
});

The .children() method differs from .find() in that .children() only travels a single level down the DOM tree while .find() can traverse down multiple levels to select descendant elements (grandchildren, etc.) as well.

Upvotes: 0

Ehsan
Ehsan

Reputation: 12959

Try this :

$("#main-nav .menu-wrapper .menu li.has-sub a:first").click(function() {

    return false;

});

Upvotes: 0

Jens Hunt
Jens Hunt

Reputation: 36

Choose first one like this

 $("#main-nav .menu-wrapper .menu li.has-sub").find( "a" ).first().click(fucntion(){
     ...
})

Upvotes: 0

Leonardo Lanchas
Leonardo Lanchas

Reputation: 1668

To select the first one is like:

 $("#main-nav .menu-wrapper .menu li.has-sub").find( "a" ).eq(0).click(function() {
    return false;
});

Upvotes: 0

Related Questions