0

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.

1
  • So you're using jQuery; why all the native DOM calls? Commented Aug 3, 2014 at 13:34

1 Answer 1

3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.