views:

48

answers:

3

So I have some code,

<div class="chunk" id="">
    <div class="chunkContent">
        <div class="textLeft" ></div>
        <div class="textRight" ></div>
        <div class="notes border">Notes...</div>
    </div>
    <div class="tools fl">
        <div class="toggleNotes border">n</div>
        <div class="addChunk border">+</div>
    </div>
</div>

Now, the two divs nested withing div.tools are small buttons. div.toggleNotes I need to select div.notes in a javascript/jquery function. div.addChunk I need to select the fisrt div, div.chunk. Currently, I am doing this by:

$(".addChunk").live('click', (function(){create_chunk(this.parentNode.parentNode)}))
$(".toggleNotes").live('click',function(){toggle_notes(this.parentNode.parentNode.firstElementChild.lastElementChild)})

Is there a better (i.e., more proper) way to do this than to string together parentNotes and firstElementChild's and etc.? I'm basically looking around the DOM tab in firebug.

+1  A: 

What about:

$("div:.addChunk").live('click', function() {
    create_chunk($(this).parent().parent());
});

$("div:.toggleNotes").live('click',function() {
    toggle_notes($(this).parent().siblings('div:.chunkContent').find('div:.notes'));
});​
Ben
+3  A: 

Since you tagged your question with jQuery, I assume you're open to using its traversal methods. This will ensure cross-browser support.

If so, you could do this:

&(".addChunk").live('click', function(){
   create_chunk($(this).closest('.chunk')); // Get closest ancestor with class 'chunk'
});

$(".toggleNotes").live('click',function(){
   toggle_notes($(this).parent().prev().find('.notes'));  // Get parent element, traverse
});                                                       //  to its previous sibling,
                                                          //  and find element with 'notes'

EDIT:

Alternatively, if you wanted, you could use .closest() for toggle_notes as well.

$(".toggleNotes").live('click',function(){
   toggle_notes($(this).closest('.chunk').find('.notes'));
});  

Relevant jQuery docs:

patrick dw
+1  A: 

You could use jQuery's .closest() selector for this, but it does seem as if you could use classes or ids to accomplish this in a less complicated way.

shipshape