Question

I have some HTML that looks likes this,

<dl class="dropdown">  
    <dt><span>Gender</span><a href="">Go</a></dt>
    <dd class="shadow_50">  
        <ul>  
            <li><a href="#"><span class="option">male</span><span class="value">1</span></a></li>  
            <li><a href="#"><span class="option">female</span><span class="value">2</span></a></li>
       </ul>  
    </dd>
 </dl>

The DD is set to be hidden when the GO link is clicked I have some code that slides the DD down or up. However my question is that when I have more than one instance if these in a page, one click opens all the DD on the page, how can I target the DD that is closest to click,

I have tried the following,

$(".dropdown dt a").click(function(e) {
    $(this).closest("dd").slideToggle(defaults.speed);
e.preventDefault();
});

and also this,

$(".dropdown dt a").click(function(e) {
    $(this).next("dd").slideToggle(defaults.speed);
    e.preventDefault();
});

I have had no success yet though.

Was it helpful?

Solution

Have you tried:

$(".dropdown dt a").click(function(e) {
    $(this).closest("dl").find("dd").slideToggle(defaults.speed);
    e.preventDefault();
});

Youc't use next() because your link has only a SPAN as a sibling and you can't use closest because it just walks up the tree

OTHER TIPS

You have the right idea, but the methods you've tried do not function quite the way you're expecting. The easiest option will probably be to go up to the parent and then find the appropriate element:

$(this).parent().next().slideToggle(defaults.speed);

Your attempts failed for the following reasons:

.closest traverses the DOM (it looks upwards, so it checks the parent, then all further ancestors until a match is found). In your case, the required element is not an ancestor of this, so that won't work.

.next gets the following sibling of the currently matched element. In your case, there isn't a following sibling as the a is the last element in the dt.

Note that if your DOM structure is likely to change you may want to use closest to reach the dl element, and then use .find to find the dd (see @Nicola Peluchetti's answer).

Try;

    $(this).parent().siblings("dd").slideToggle(defaults.speed);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top