15

I want to change a class onclick. What I have at the moment:

<script>
function changeclass() {

var NAME = document.getElementById("myclass")

NAME.className="mynewclass"

} 
</script>

But, ofcourse, its not working. Also, it should revert to previuos state onclick again.

My html:

<div id="showhide" class="meta-info" onclick="changeclass();">

So, whenever I press on #showhide myclass should change to mynewclass. Thanks for help in advance!

2
  • You use getElementById. This function takes the id an element, not its class. Commented Aug 10, 2011 at 16:34
  • getElementById namely "myclass" but anyways, in the HTML you use he ID showhide. Why? Commented Apr 4, 2022 at 0:43

8 Answers 8

36

With jquery you could do to sth. like this, which will simply switch classes.

$('.showhide').click(function() {
    $(this).removeClass('myclass');
    $(this).addClass('showhidenew');
});

If you want to switch classes back and forth on each click, you can use toggleClass, like so:

$('.showhide').click(function() {
    $(this).toggleClass('myclass');
    $(this).toggleClass('showhidenew');
});
Sign up to request clarification or add additional context in comments.

7 Comments

How this script should look if my showhide is not an id, its <div class = "showhide"> and my new class would be showhidenew ?
This doesn't make a lot of difference. Changing from id(#) to class(.)changes your selector from #showhide to .showhide. The renaming of the new Class can simply be copied to the addClass / toggleClass, if you use the latter. See my edit.
Do I have to add something like onclick()? Or it should work like this whenever I press on clas .showhide?
I know that your variant is correct, but in my case it just doesnt work somehow.
Can you post your code somewhere (e.g. on jsfiddle.net) or post a link to your actual page? Then I can help you more precisely.
|
7

Your getElementById is looking for an element with id "myclass", but in your html the id of the DIV is showhide. Change to:

<script>
function changeclass() {

var NAME = document.getElementById("showhide")

NAME.className="mynewclass"

} 
</script>

Unless you are trying to target a different element with the id "myclass", then you need to make sure such an element exists.

Comments

6

For a super succinct with jQuery approach try:

<div onclick="$(this).toggleClass('newclass')">click me</div>

Or pure JS:

<div onclick="this.classList.toggle('newclass');">click me</div>

8 Comments

I liked the idea of this approach INLINE. But this specific syntax does not work, how can you have double quotes like that $(this) errors. etc etc Can you provide an edit here with a working example
Good spot, fixed using single quotes
Yes, but it still does not work, I am no JS expert, still learning, but this simple example as much as it seems like a great idea it does not work for me. I get "Uncaught ReferenceError: $ is not defined at HTMLButtonElement.onclick" Please see for yourself... you can inspect for the console error. w3schools.com/code/tryit.asp?filename=G9JA8STH3SSP
If $ is not defined sounds like you've not added jQuery to the page.
I've added an alternate solution that doesn't require jQuery
|
1

Just using this will add "mynewclass" to the element with the id myElement and revert it on the next call.

<div id="showhide" class="meta-info" onclick="changeclass(this);">

function changeclass(element) {
    $(element).toggleClass('mynewclass');
}

Or for a slighly more jQuery way (you would run this after the DOM is loaded)

<div id="showhide" class="meta-info">

$('#showhide').click(function() {
    $(this).toggleClass('mynewclass');
});

See a working example of this here: http://jsfiddle.net/S76WN/

2 Comments

Chad, how this script should look if my showhide is not an id, its <div class = "showhide"> and my new class would be showhidenew ?
You would change the jQuery selector $('#showhide') to something correct like $('.showhide') and the class in toggleClass to showhidenew.
1
      <div class="liveChatContainer online">
        <div class="actions" id="change">
         <span class="item title">Need help?</span>
              <a href="/test" onclick="demo()"><i class="fa fa-smile-o"></i>Chat</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Call</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Email</a>
        </div>
              <a href="#" class="liveChatLabel">Contact</a>
     </div>
             <style>
               .actions_one{
               background-color: red;
                      } 
              </style>



           <script>
          function demo(){
      document.getElementById("change").setAttribute("class","actions_one");}
            </script>      

Comments

0

I would think this: http://jsfiddle.net/Skooljester/S3y5p/1/ should do it. If I don't have the class names 100% correct you can just change them to whatever you need them to be.

1 Comment

How this script should look if my showhide is not an id, its <div class = "showhide"> and my new class would be showhidenew ?
0

Another example is:

$(".myClass").on("click", function () {
   var $this = $(this);

   if ($this.hasClass("show") {
    $this.removeClass("show");
   } else {
    $this.addClass("show");
   }
});

Comments

0

I think you mean that you want want an onclick event that changes a class.

Here is the answer if someone visits this question and is literally looking to assign a class and it's onclick with JQUERY.

It is somewhat counter-intuitive, but if you want to change the onclick event by changing the class you need to declare the onclick event to apply to elements of a parent object.

HTML

<div id="containerid">
     Text <a class="myClass" href="#" />info</a>
     Other Text <div class="myClass">other info</div>
</div>
<div id="showhide" class="meta-info">hide info</div>

Document Ready

$(function() {
     $("#containerid").on("click",".myclass",function(e){ /*do stuff*/ }
     $("#containerid").on("click",".mynewclass",function(e){ /*do different stuff*/ }
     $("#showhide").click(function() {changeclass()}
});

Slight Tweak to Your Javascript

<script>
function changeclass() {
        $(".myClass,.myNewClass").toggleClass('myNewClass').toggleClass('myClass');
} 
</script>

If you can't reliably identify a parent object you can do something like this.

$(function() {
     $(document).on("click",".myclass",function(e){}
     $(document).on("click",".mynewclass",function(e){}
});

If you just want to hide the items you might find it simpler to use .hide() and .show().

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.