Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Removing class when another div is clicked

Hi,

I want to know how if I append a div by clicking at the button like:

$('button').click(function(){
    $('body').append('<div class='class'></div>'); 
});

And if I click at the button again another div will append, and what I want is when I click for example "div 1" a class will be added to it "class_selected" and when I click on "div2" "class_selected" should get removed from "div1"

I am really finding a lot of troubles for knowing how to do that.

I got something like this to work. In orer to add click events to items that dont exist when DOM is loaded you need to use delegate()

http://api.jquery.com/delegate/

jQuery(document).ready(function($) {

  $("#moreInfo").click(function() {
    $('body').append('<div class="foo" />')
  });

  $( "body" ).delegate( ".foo", "click", function() {
    $(this).siblings().removeClass('selected');
    $(this).addClass('selected');
  });

});

@Chris Warr Really thank you for helping me it worked perfectly. Just post it as an answer so I can vote and give you the best answer

1 Answer

I got something like this to work. In orer to add click events to items that dont exist when DOM is loaded you need to use delegate()

http://api.jquery.com/delegate/

jQuery(document).ready(function($) {

  $("#moreInfo").click(function() {
    $('body').append('<div class="foo" />')
  });

  $( "body" ).delegate( ".foo", "click", function() {
    $(this).siblings().removeClass('selected');
    $(this).addClass('selected');
  });

});