简体   繁体   中英

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.

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() {
  // ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM