jQuery select element immediately next to another

746 Views Asked by At

If I have:

<dt>Title</dt>
<dd>Description</dd>

<dt>Title</dt>
<dd>Description</dd>

<dt>Title</dt>
<dd>Description</dd>

<dt>Title</dt>
<dd>Description</dd>

How can I make a selector, so that when I click a dt, the dd immediately after (and only that DD) it is given a class name? I have tried nextUntil() and next() with no success

This is to make something I am working on more efficient

Thanks for any help

3

There are 3 best solutions below

0
On

Without knowing how your js-code looks like, something like this might work for you?

http://jsfiddle.net/GwpNp/

$("#wrapper").on("click", "dt", function(e){
   $(this).next().addClass("red");
});

<div id="wrapper">
    <dt>Title</dt> <dd>Description</dd>  
    <dt>Title</dt> <dd>Description</dd>  
    <dt>Title</dt> <dd>Description</dd>  
    <dt>Title</dt> <dd>Description</dd>
</div>
0
On

next() should work ok - a click handler for the 'dt's along these lines should do the trick:

function dtClicked() { $(this).next().addClass("new-class"); }

0
On
<script type="text/javascript">
    $(document).ready(function(){
        $('dt').click(function(){
            $(this).next('dd').addClass('bolder');
        });
    });
</script>

<style>
    .bolder {
        font-weight: bold;
    }
</style>