Search code examples
javascriptjquerythisaddclassselected

how to get element id on click without any inline function call in javascript?


I need to change the element's class clicked upon to 'selected' This is a part of my html file:

<div class="side-nav white-nav" id="sidenavblade">
 <ul>
      <span id="trigger-1" class="menu-trigger"><li>
        <a href="<?php echo URL::to('/')."/initiatives" ?>" class="">
          <span id="trigger-1" class="menu-trigger" >INITIATIVES <i class="icon initiatives"></i>
        </a>
      </li></span>....

there are 10 more 'li' in the class 'side-nav' I need to change the class of icon to 'selected' for the 'a' element clicked upon. My js :

var select=false;
t=document.getElementById('sidenavblade');
e=t.getElementsByTagName('a');

$(e).click(function(){
  if(select==true){
     $('.selected').removeClass('selected');
  }
  $(this).getElementsByClassName('icon ').addClass('selected');
  select=true;
});

But, 'this' comes out to be 'undefined'. How can I change my function to get the element clicked upon, without calling the function for each element separately.


Solution

  • You're mixing jQuery and native DOM calls for no apparent reason. This just won't work:

     $(this).getElementsByClassName('icon ').addClass('selected');
    

    However, it's easy with the library:

     $(this).find('.icon').addClass('selected');
    

    The DOM API returns a NodeList, and you can't use it like a jQuery object.

    Similarly:

    e=t.getElementsByTagName('a');
    
    $(e)
    

    might work, but I'm not sure; certainly it's simpler to just write

    $('a').click(function() {
      // ...