jQuery : selecting a parent when a click event is fired on a child

In jQuery, I’m a bit confused as to how to select a parent element to a child if I attached a click event on the parent but also want a click event on a child within.

Let’s say I have a the following code :


<div class="clickclass">
Some content
</div>

There may be several of those classes in the page. I then use jQuery to replace the inner HTML to the clickclass div when clicked on with some other code and a input button (with an ID of, let’s say ‘save_button’). This works fine for that part:


$('.clickclass').click(function () {
  // If the event is triggerd form 'clickclass', then replace with HTML + input button
  $(this).html('some html code + <input type="submit" name="save_button" id="save_button" value="Save" />');
});

I then want to have the button clickable so that I can replace again the HTML in the div (like a save button). But if I try a separate event listener on the input button, it also fires the parent event. Even if I return false on the child event or use event.stopImmediatePropagation() in the .click child function.

I’ve managed to almost get it with the following code :


$('.clickclass').click(function (event) {
  // If the input button is clicked, get the parent with class 'clickclass' and replace with other HTML.
  if (event.target.id == 'save_button') {
     myparent = event.target.parent();
     myparent.html('some html code');
  }

  // If the event is triggerd form 'clickclass', then replace with HTML + input button
  $(this).html('some html code + <input type="submit" name="save_button" id="save_button" value="Save" />');
});

The problem is that whenever I try using .parent() with jQuery, it always tells me that parent() is not a function. I’ve tried various other ways of getting the parent object (the clickclass div) but can’t get it to work. Any idea? Thanks!

Try $(event.target).parent()

I had tried that but although it returns and object, whenever I try to find out if it’s really the containing div by doing :


myparent = $(event.target).parent();
alert(myparent.id);

I always get ‘undefined’. Shouldn’t it give out ‘clickclass’ instead? Is there a way to see what object is returned? It just says [object Object] whenever I alert the object myparent. Thanks!

$(event.target).parent() returns a jQuery object. That object does not have an id property. Try this:


alert(myparent.attr('id'));
// Or:
alert(myparent[0].id);

Aahhhhh… a jQuery object, not the object per se! Works great now, thank you! :slight_smile: