user311166
user311166

Reputation: 43

JQuery : Selecting unknown child element

I have a dictionary list and I want to access the 2nd child element without knowing what element it is. For example:

    <dl>
        <dd>
            <div></div>
            <div></div> (select this item - however can be any html element)
       </dd>
       <dd>
            <div></div>
            <div></div> (select this item - however can be any html element)
       </dd>
       <dd>
            <div></div>
            <div></div> (select this item - however can be any html element)
       </dd>
    </dl>

I tried ...

    $('dd').each(function() {
        $(this + ':nth-child(2)').addClass('hover');
    }

I tried this with a series of different number 0-2 trying to find the element. 0 puts the class in all first child html tags. For example:

    <html class="hover">
    <body class="hover">
        <div class="hover"> 

... etc. Not what I want btw. Leading me to believe that $(this) is actually targeting the window and not my individual dd elements.

Anyway if anyone can shed some light I would greatly appreciate it. Thanks.

Upvotes: 1

Views: 1419

Answers (2)

Alnitak
Alnitak

Reputation: 339786

There's no need for a .each() call - most jQuery functions work happily on lists of elements.

Just match all .children() of a <dd> that are the 2nd child of their parent, and add the required class:

$('dd').children(':nth-child(2)').addClass('hover');

working demo at http://jsfiddle.net/alnitak/TETbE/

or (thanks to @ChrisPratt) you can combine the selectors:

$('dd > :nth-child(2)').addClass('hover');

Upvotes: 1

Chris Pratt
Chris Pratt

Reputation: 239240

The problem is just your syntax. Try:

$('dd').each(function() {
    $(':nth-child(2)', this).addClass('hover');
}

Upvotes: 3

Related Questions