Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class using jQuery?

Tags:

jquery

css

I made a small function whose work to do add class in <li> when we clicks on <li>, but I want to remove that if it is already had with <li>.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    <meta name="generator" content="CoffeeCup HTML Editor (www.coffeecup.com)">
    <meta name="created" content="Tue, 22 May 2012 12:39:23 GMT">
    <meta name="description" content="">
    <meta name="keywords" content="">
    <title></title>

    <style type="text/css">
    <!--
    body {
      color:#000000;
      background-color:#FFFFFF;
    }
    a  { color:#0000FF; }
    a:visited { color:#800080; }
    a:hover { color:#008000; }
    a:active { color:#FF0000; }
    -->
    </style>

    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>

    <script type="text/javascript">

    $(function(){

    $('.main').find('li').each(function(){

    $(this).live('click', function (){

    $(this).addClass('active')

    })

    })

    })

    </script>

  </head>
  <body>

  <ul class="main">
  <li>first</li>

  <li>second</li>
    <li>third</li>
      <li>fourth</li>  

  </ul>

  </body>
</html>
like image 206
Jitender Avatar asked May 22 '12 12:05

Jitender


People also ask

How can I add class in jQuery?

jQuery addClass() Method The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

Can I use class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do you append a class in JavaScript?

Using . add() method: This method is used to add a class name to the selected element. Syntax: element.

How do I add a class in CSS?

If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.


1 Answers

You can just use toggleClass this will add or remove it as necessary

$('.main li').live('click',function(){
  $(this).toggleClass('active');
});

if you want to remove this class from elsewhere, you can add an extra line:

$('.main li').live('click',function(){
  $('.main li.active').removeClass('active')
  $(this).addClass('active');
});
like image 107
Jamiec Avatar answered Sep 25 '22 23:09

Jamiec