Evanss
Evanss

Reputation: 23613

Easiest way for complicated DOM traversing?

Below is my code that shows a very simple scenario with multiple triggers and targets. Clicking div.trigger 1 will change the color of div.target 1, and clicking div.trigger 2 will change the color of div.target 2.

My actual html is far more complicated so instead of just using one next(), I will need to use a lot of methods to traverse the DOM. When in this situation is there some other way of tackling the problem?

It would also be great if the code was more robust so that if the relative html structure of the trigger and target elements changed it would still work. For instance if there was something like the eq function that made the 1st div.trigger target the 1st div.target, and the 2nd div.trigger target the 2nd div.target regardless of the html of the rest of the page.

 <div class="trigger">trigger 1</div>
 <div class="target">target 1</div>
 <div class="trigger">trigger 2</div>
 <div class="target">target 2</div>

 ​$(document).ready(function(){
     $('.trigger').click(function(){
         $(this).next().css('background-color','red');        
     }); 
 });​

http://jsfiddle.net/5tcNq/2/

Thanks

Upvotes: 1

Views: 55

Answers (2)

Stefan
Stefan

Reputation: 5662

You can use data to store a reference to the target element.

<div id="trigger1" class="trigger" data-target="#target1">trigger 1</div>
<div id="target1" class="target">target 1</div>

​$(document).ready(function(){
     $('.trigger').click(function(){
         var $target = $($(this).data('target'));
         $target.css('background-color', 'red');
     });
});​

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123397

...for instance if there was something like the eq function that made the 1st div.trigger target the 1st div.target, and the 2nd div.trigger target the 2nd div.target...

try this code: http://jsfiddle.net/JGyc9/

relevant js:

$(function() {

   var tr = $('.trigger'),
       tg = $('.target');

   tr.on('click', function() {
      var i = tr.index(this);
      /* tg.eq(i) is the target */


      console.log("your trigger ", $(this).text());
      console.log("your target ", tg.eq(i).text());
   });
});

Upvotes: 1

Related Questions