views:

37

answers:

2

Using jQuery I need to select elements that are:
under the "menu" DIV only
AND are DT elements
AND are followed by a DD element

In this sample HTML I would only want to select ids "select_me1" and "select_me2"

<html><body>
    <div id="menu">
        <dl>
            <dt id="dont_select1"><a href="#">don't 1</a></dt>
        </dl>
        <dl>
            <dt id="dont_select2"><a href="#">don't 2</a></dt>
        </dl>
        <dl>
            <dt id="dont_select3"><a href="#">don't 3</a></dt>
        </dl>
        <dl>
            <dt id="select_me1"><a>select me 1</a></dt>
            <dd id="community-sub">
                <ul>
                    <li><a href="#">Sub 1</a></li>
                    <li><a href="#">Sub 2</a></li>
                    <li><a href="#">Sub 3</a></li>
                </ul>
            </dd>
        </dl>
        <dl>
            <dt id="select_me2"><a>select me 2</a></dt>
            <dd id="state-sub">
                <ul>
                    <li><a href="#">Sub 4</a></li>
                    <li><a href="#">Sub 5</a></li>
                    <li><a href="#">Sub 6</a></li>
                </ul>
            </dd>
        </dl>
    </div>
    <div id="other">
        <dl>
            <dt id="else1"><a href="#">else 1</a></dt>
        </dl>
        <dl>
            <dt id="else2-main"><a>else 2</a></dt>
            <dd id="else2-sub">
                <ul>
                    <li><a href="#">Sub 1</a></li>
                    <li><a href="#">Sub 2</a></li>
                </ul>
            </dd>
        </dl>
    </div>
</body>
</html>

Please help! Thanks.

+3  A: 

You can go a bit backwards here, like this:

​$("#menu dd").prev("dt")

You can test it out here. This goes to #menu using an #ID selector, finds all descendant <dd> elements with an element selector then uses .prev() to go back to the <dt> sibling that immediately precedes it, if there is one.

Nick Craver
Too slow again ;) .... +1
Felix Kling
Thanks. Worked perfectly.
Young Fu
Why is would "this" within $("#menu dd").prev("dt").each{} give me an array of length 1 rather than the dt element itself??
Young Fu
@Young - `this` should refer to the element, you can test here: http://jsfiddle.net/nick_craver/MBHCz/2/
Nick Craver
A: 

This will select <dd> elements that have a previous <dt> element. Then it uses .prev() to traverse back to its sibling <dt>.

$('#menu dt + dd').prev()
patrick dw