0

I want to select an element whose id matches the href of an <a> element

HTML

<a href="web"></a>
<a href="app"></a>

<div id="web"></div>
<div id="app"></div>

jQuery

$('a').on('click', function(e) {
   e.preventDefault();
   var $href = $(this).attr('href');
   var $id = $('div').attr('id');
   $(this).addClass('active');
   //HERE I WANT TO SELECT THE DIV WHOSE "id" MATCHES THE "href" of the <a> clicked 
   $('div').id($href).addClass('active');
});
gustavozapata
  • 429
  • 2
  • 7
  • 13

1 Answers1

0

Add a leading # to the $href to get the selector of the div like following.

$('a').on('click', function (e) {
    e.preventDefault();
    var $href = $(this).attr('href');
    $(this).addClass('active');

    $('#' + $href).addClass('active'); // this is what you need to do
});
Ibrahim Khan
  • 20,616
  • 7
  • 42
  • 55