开发者

Can we edit an exsiting class of an element using jquery?

I want to alter styles of an existing class of an element. Can we do this in Jquery? If not, what开发者_开发技巧 can be the alternate approach ?


I don't believe it's possible to edit a class using jQuery, and you shouldn't have to in any case, as all of the styles you want to use should already be defined in your style sheet. You don't want to have to edit, both, JS files and CSS files in order to change your styles later on.

But if you absolutely have to, or if this is less of style change than a UI behavior (e.g. you want hide all elements of the .warning class, then you could simply do something like:

$(".warning").css('display', 'none');

But aside from hiding/showing elements, you generally want to just change the class(es) of an element using addClass() / removeClass() / toggleClass() as others have mentioned.


yes you can alter class with toggle method and to chage style of element you can use .css() method of jquery.

Example :

<!DOCTYPE html>
<html>
<head>
  <style>
  ul { margin:10px; list-style:inside circle; font-weight:bold; }
  li { cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.min.js"></script>
</head>
<body>
    <ul>
    <li>Go to the store</li>
    <li>Pick up dinner</li>
    <li>Debug crash</li>

    <li>Take a jog</li>
  </ul>
<script>
    $("li").toggle(
      function () {
        $(this).css({"list-style-type":"disc", "color":"blue"});
      },
      function () {
        $(this).css({"list-style-type":"disc", "color":"red"});
      },
      function () {
        $(this).css({"list-style-type":"", "color":""});
      }
    );

</script>
</body>
</html>


You can add classes to an element with jQuery using the .addClass function and you can remove them with the .removeClass function.

There's also a function to toggle between adding and removing the class. It's called - you guessed it - toggleClass.

See the jQuery documentation for these:

http://api.jquery.com/addClass/

http://api.jquery.com/removeClass/

http://api.jquery.com/toggleClass/

You can also set css styles explicitly with the .css function, but that doesn't do anything with classes, so I'm not sure if that's what you're looking for:

http://api.jquery.com/css/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜