-1

Consider the following HTML:

<div class="group">
    <div class="select">Project Type</div>
    <div class="option">
        <div>Personal Website</div>
        <div>Business Website</div>
        <div>Hosting</div>
        <div>Social Media</div>
        <div>Online Storefront</div>
        <div>Graphics & Branding</div>
    </div>
</div>

Here is my working jQuery:

var item = $('.option').find('div');

item.on('click', function(event){
    var test = $(this).parent().prev('.select');

    console.log( test );
});

This works, but my problem is that I don't think this is very flexible, as it can easily break if I re-arrange the code in any way, as .select must be adjacent and previous to the .option or it breaks.

Does anyone have any good solutions that could help me traverse the DOM tree a little more dynamically, so as not to depend on the exact order of the HTML elements?

Xenostar
  • 165
  • 2
  • 3
  • 11
  • 4
    You should use instead: `$(this).closest('.group').find('.select')` which is more flexible https://api.jquery.com/closest/ – A. Wolff Apr 07 '15 at 19:36
  • 1
    By the way, `item.on('click', function(event){...})` makes *separate* binding to every children `
    ` inside of `
    `. Why you don't use `$('.option').on('click', function(event){...})`? Inside of event handler you can use `event.target` to get the children `
    ` element which is clicked. The `$(this).prevAll('.select')` or `$(this).closest('.group').find('.select')` inside of event handler will get your the div.select element.
    – Oleg Apr 07 '15 at 19:45

1 Answers1

0
$(".group").on('click', '.option div', function(event) {
    // event.delegateTarget is always .group element
    var test = $(event.delegateTarget).find('.select');
    console.log(test);
    console.log('Clicked option:', this);
});

Read more about delegated on() and delegateTarget.

Community
  • 1
  • 1