Search code examples
javascriptjquerytabsselectorhref

jQuery cant access element with its attr href // simple tabs structure


I can't access "a" element with its href. Like this example, i need add class to element which got href="#one"

Here is jsFiddle.

jQuery:

//tabs part is working fine
$('.tabs').hide();
$('.tabs:first').show();
$('ul li a').click(function(){
   var target = $(this).attr('href');
    $('.tabs').hide();
    $(target).fadeIn(500);

   $('ul li a').removeClass('selected');
   $(this).addClass('selected');
});

   //problem starts when i try to reach href
   var link1 = '#one';
   var link2 = '#two';
   var link3 = '#three';

   var takE = $('ul li a').each();
   var finD = take.attr('href');
   finD.addClass('thisisLink1');​

html:

<ul>
    <li><a href="#one">Home</a></li>
    <li><a href="#two">Posts</a></li>
    <li><a href="#three">About</a></li>
</ul>
<div class="tabs" id="one">Home Container</div>
<div class="tabs" id="two">Posts Container</div>
<div class="tabs" id="three">About Container</div>​

I have tried each method but it didn't work. I need to access elements with their attr href and set the object to addClass or animate. This way returns me as a string.


Solution

  • $('ul li a').each(function() {
      if(this.href == link1) $(this).addClass('thisisLink1');
      if(this.href == link2) $(this).addClass('thisisLink2');
      if(this.href == link3) $(this).addClass('thisisLink3');
    });
    

    You can also use an object mapping:

     var links = {
        '#one': 'thisislink1',
        '#two': 'thisislink2',
        '#three': 'thisislink3',
    };
    $.each(links, function(key, val) {
        $('ul li a[href="' + key + '"]').addClass(val);
    });
    

    DEMO