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');
});
0

1 Answer 1

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
});
Sign up to request clarification or add additional context in comments.

3 Comments

That's it! The thing is, what $('#' + $href) does?
$('#' + $href) selects the div which id is same as the cliked <a>'s href. @tavozapata
Oh I see, I'd never have imagined that the addition sign would do that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.