user2954467
user2954467

Reputation: 95

jquery specify child and parent

I am having a problem where my code is not recognizing the parent as "ul" and is instead seeing it as the class. The child has wider effects than I believe it should.

Segments of the code:

<script>
       $(document).ready(function(){
        $("div:last").click(function(){
            $("ul").parent(".northern").children(':nth-child(3)').hide();
            });
        });
    </script>

<section class="northern">
            <h2>US</h2>
            <ul>
                <li>Princeton</li>
                <li>Harvard</li>
                <li>Yale</li>

            </ul>
            <div>
                <input type="button" value="Click Me!">
            </div>
        </section>

Upvotes: 0

Views: 54

Answers (2)

Barmar
Barmar

Reputation: 780787

You seem to think that $("ul").parent(".northern") means find the UL whose parent has class = northern. What it actually means is find all ULs, then find all their parents that have class = northern. .parent() is a DOM traversal method, not a filter.

What you presumably want is:

$(".northern > ul").children(':nth-child(3)').hide();

Upvotes: 2

Use .closest()

$(document).ready(function () {
    $("div:last").click(function () {
        $("ul").closest(".northern").children(':nth-child(3)').hide();
    });
});

I think OP want 3rd li item

Fiddle DEMO

$(document).ready(function () {
    $("div:last").click(function () {
        $(".northern ul").children(':nth-child(3)').hide();
    });
});

Upvotes: 0

Related Questions