how to use next() to find the closest ul in jquery?
Asked Answered
C

3

8

i have a simple menu, something like this:

<ul id="navigation">
    <li id="m_li">
         <div><span>+</span><a href="#" >myself</a></div>
        <ul class="test" id="x_ul">
            <li id="li">
                <a href="#" >Pictures</a>
            </li>
            <li id="li">
                <a href="#" >Audio</a>
            </li>
        </ul>
    </li>
    <li id="profile_modeling_li">
        <div><span>+</span><a href="#" >friend</a></div>
        <ul class="test" id="y_ul">
            <li id="li">
                <a href="#" >Pictures</a>
            </li>
            <li id="li">
                <a href="#" >Video</a>
            </li>
        </ul>
    </li>
</ul>

then i use jquery so when i click on the + sign the ul slides down:

$("#navigation > li > div > span").click(function(){

    if(false == $(this).next('ul').is(':visible')) {
        $('#accordion ul').slideUp(300);
    }
    $(this).next('ul').slideToggle(300);
});

the issue is that $(this).next('ul') doesn't seem to fond the next ul

any ideas what am i doing wrong?

Canonicate answered 24/4, 2012 at 18:38 Comment(2)
You could use $(this).find('ul')Lexical
No, you can't.find looks into the elements descendants while in this case, the ul is the sibling of the element's parent.Prader
P
13

use

$(this).parent().next()

instead of

$(this).next();

and, of course, you can pass a selector (more simple or more complex) that identifies the desired element as argument:

$(this).parent().next('ul.test[id$="_ul]"'); 
Prader answered 24/4, 2012 at 18:41 Comment(0)
M
3

.next / .prev traverse through siblings and ul is not a children of the span. You should probably find closest li and find .test.

 $(this).closest('li').find('ul.test')
Milden answered 24/4, 2012 at 18:42 Comment(2)
.next() and .prev() traverse through siblings, not children.Purehearted
@AnthonyGrist aaw.. i meant siblings but wrote as children. Thanks for pointing it out.Milden
C
1

Convert

$(this).next('ul')

to

$(this).parent().next('ul')

You can see here http://jsfiddle.net/PYqS2/

Courtroom answered 24/4, 2012 at 18:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.