Nested click in jQuery


I have a DIV that when click on it, it will add another DIV inside itself. Then if I click the newly added DIV it will remove it.


<div id="container"></div>


$('#container').on('click', function(e){ // Add other DIV $( this ).append('<div class="other">XYZ</div>'); e.stopPropagation(); // Remove other DIV $('div.other').bind('click', function(event){ $( this ).remove(); event.stopPropagation(); }); });

How efficient is this method if I plan to have to lot of child DIVs?


Attaching events when another event fires will likely cause some unintentional side effects, and subject your DOM to memory leaks.

As a general rule, attach handlers once, run often.

$(document) .on('click', '#container', function(e) { // Add other DIV $(this).append('<div class="other">XYZ</div>'); }) .on('click', 'div.other', function(e) { $(this).remove(); e.stopPropagation(); });


I would slightly change the JQuery so you can chain off the selector for the .append, and use .on instead of .bind:

$('#container').on('click', function(e){ // Add other DIV $( this ).append( $('<div>').attr('class', 'other') .html('XYZ') // Remove other DIV .on('click', function(event){ $( this ).remove(); event.stopPropagation(); }); ) e.stopPropagation(); });

It's untested code, but it should be functionally identical to yours. I would avoid binding on $(document) because it is inefficient due to firing events on the entire DOM. Parsing the DOM is the most time-consuming part of Javascript code execution, which is why reusing JQuery selectors as I just have is also more efficient.


It probably doesn't need any optimisation because it doesn't do a lot of thing. but if you want it to be <em>optimal</em> without using vanilla JS, I would go like this :

var $myDiv = $('<div class="other">XYZ</div>'); //Cache the div instead of creating it every click $('#container').on('click', function(e){ if($myDiv.is(e.target)) //Check if your div is the clicked target $myDiv.remove(); //Remove the div else $myDiv.appendTo(this) // Else append the div. }); <hr />

Just note that if the div contain children element, the if should be changed to :



  • Javascript: Mixing in a getter (object spread)
  • Through presenting new view controller viewWillDisappear on parent is triggered where I unsubscribe
  • How can I fill all space of a div 100% with 3 divs with the same size?
  • QTP UFT Unable to find row count from table
  • Mod rewrite redirection to another domain if file not exist
  • Redis under Classic ASP(VBScript)
  • SSH in Bash Script Messing Up File Read
  • C++/CLI Thread synchronization including managed and unmanaged code
  • How many Vertica Databases can run on a Host in the same time?
  • Passing information to server-side function in a Google Docs Add On
  • How to create virtual printer with iOS Simulator?
  • CloseOptionsMenu doesn't work?
  • Is is safe to use HSQLDB for production? (JBoss AS5.1)
  • Is there a way to call library thread-local init/cleanup on thread creation/destruction?
  • Distributed JMS based logging .. falling flat?
  • What is this strange character in chrome's resource css viewer?
  • Application bar icon text length
  • Python/Javascript: WYSIWYG html editor - Handle large documents fast and/or design theory
  • Regex for Specific Tag
  • Motorola barcode scanner SDK events C#
  • Accessing Rows In A LINQ Result Without A Foreach Loop?
  • Why doesnt this Java loop in a thread work?
  • Android onKey w/ virtual keyboard
  • how to get data attributes of dynamically generated element
  • How can we prepend rows to a react native list-view?
  • android google indoor map
  • Can someone please explain to me in the most layman terms how to use EventArgs?
  • Remove changes from one element when event occurs on another element?
  • What's the purpose of QString?
  • Detect when Facebook like button is clicked
  • how to display data from 1st point on words on y axis for line chart in d3.js
  • Jackson Parser: ignore deserializing for type mismatch
  • Row Count Is Returning the incorrect number using RaptureXML
  • Xamarin Forms - UWP Fonts
  • Azure Cloud Service Web Role web pages do not load
  • WinForms: two way TextBox problem
  • Javascript convert timezone issue
  • Free memory of cv::Mat loaded using FileStorage API
  • Angular 2 constructor injection vs direct access
  • Programmatically clearing map cache