Appending Div Tags To The DOM, The Right Way.

Sometimes we want to generate divs on the fly and append them to the DOM. Many times I have seen people (I have done it myself too) adding divs using plain text such as

$('#item').append('<div class="button" id="button-id">Delete</div>');

A  cleaner way to do it would be:

var button = $('<div>', {
  class: 'button',
  id: 'button-id',
  text: 'Delete',
    'cursor': 'pointer'


The cool thing about this method is that you can easily add bindings to this newly created div (or button in this case).

For instance, let’s say I generated a button on the fly, and I wanted to add a click event to it. All I have to do is to add my event handler to it.

button.on('click', function(){
//add your code here
console.log('Button was clicked');

Posted on: August 31st, 2013 by Stephani

Leave a Reply