September 3, 2013

How to apply css class for selected element in jquery or javascript?

User2563516’s Question:

I am new to Jquery any one tell me how to select child elements
please check my code

<ul class="orglisting">
   <li><a href="javascript:getOrgUsers();" class="orglistactive">orgName</a></li>
   <li>
      <a href="javascript:getOrgUsers();">orgName1</a>
      <ul id="dId">
         <li id="dId1"><a href="javascript:getDeptUsers('Sales','1','1');">Sales</a></li>
         <li id="dId2"><a href="javascript:getDeptUsers('Engineering','1','1');">Engineering</a></li>
      </ul>
   </li>
   <li>
      <a href="javascript:getOrgUsers();">orgName2</a>
      <ul id="dId">
         <li id="itbhanu"><a href="javascript:getDeptUsers('ITbhanu','1','1');">ITbhanu</a></li>
      </ul>
   </li>
   <li>
      <a href="javascript:getOrgUsers();">orgName3</a>
      <ul id="dId">
         <li id="Engineering"><a href="javascript:getDeptUsers('PvtLtd','Engineering','1','1');">Engineering</a></li>
      </ul>
   </li>
</ul>

My problem is when i am select deparmentName i want to select change background color for parent tag(orgName) and selected deartmentName.

For Example i am selected in orgName1(orgName) in that i selected Enginnering (department) i want to change backgroundcolor for orgName1 and Engineering and again i selected orgName2 (orgName) and departmentName is ItBhanu i want to apply background color for those two and remove before apply background color.

How can i do this..

If I understand you correctly you are trying to remove some style from previous elements and apply news elements to New Ones.

First of all, create a class which shows elements has selected, something like:

.selected { background: #ddd; }

Then on jQuery you have to attach to the click event of your anchor a tags.

$("a").on('click', function() {
   //Now this is run when all `a` will be clicked

   //First lets remove selected class from previously selected items

   $('.selected').removeClass('selected');

   // And lets add selected to currect element and this parent

   $(this).addClasss('selected');
   $(this).parent('li').find('a:first').addClass('selected');


});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!