0

I need a script that adds a 2 to the end of a class in a div with the id .sideboxtopleft on clicking of a link with the id of posts.

<script>
    $(".posts").click(function () {
      if ($('.sideboxtopleft').is('#sideboxtopleft2')) {
          $('.sideboxtopleft').removeClass('2');
      }
      else{
          $('.sideboxtopleft').addClass('2');
      }
    });
</script>

<div id="sideboxtopleft" class="sideboxtopleft">
<a href="#post" id="posts"><h3>RECENT POSTS <div id="arrow" class="arrow"></div></h3></a>
</div>
<div id="sideboxtopright" class="sideboxtopright">
<a href="#comments" id="comments"><h3>RECENT COMMENTS <div id="arrow" class="arrow2"></div></h3></a>
</div>

However it doesn't seem to want to work properly. Any help?

1
  • You do realize that the class 2 (CSS ".2") has nothing to do with the ID sideboxtopleft2 (CSS "#sideboxtopleft2"), right? Perhaps you just mean to use the selector: "#sideboxtopleft.2" -- also, avoid using the same class and ID names unless there is a very good reason to! Commented Jun 18, 2010 at 4:53

2 Answers 2

2

You can do it using .toggleClass() like this:

$(".posts").click(function () {
  $('.sideboxtopleft, .sideboxtopleft2').toggleClass('sideboxtopleft sideboxtopleft2');
});

All of the class methods add, remove, or toggle entire classes, they don't append/remove part of a class name. Though the above code works, it isn't the most ideal solution, a multi-class selector in CSS is probably a better approach, like this:

.sideboxtopleft { color: black; }
.sideboxtopleft.on { color: red; }

Then you could just toggle the on class, like this:

$(".posts").click(function () {
  $('.sideboxtopleft').toggleClass('on');
});
Sign up to request clarification or add additional context in comments.

Comments

0

Why not just add a new class to tag?

<div id='foo' class='sideboxtopleft two'>

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.