Joe.wang
Joe.wang

Reputation: 11793

Two ways of build html -- .html() and .append()

In jQuery, I know we can replace an object's HTML using .html(html code here), and we can also use one of the methods (append, appendTo, prepend, etc.) to achieve the same goal of .html(...).

But what is the difference between these two ways?

Updated

I think I should post my code to make my question more clearly, please review it.

$('<a>close</a>').click(function() {
            alert("test");
        }).appendTo($('.widget-head'));

var sHtml = $('.widget-head').wrap('<p>').parent().html();
$(currentTmpContainer).html(resultHtml);

(This is just a code snippet. I think you would be okay understanding it. Thanks.)
Finally, I found that .click didn't work in my example. I guess the reason is because I am using .html() instead of .append(). Is it correct? Thanks.

Upvotes: 1

Views: 86

Answers (2)

emurano
emurano

Reputation: 973

I tend to use .html() for changing the text of an element. E.g.

$('.myElement').html('Hello, World!');

Which results in something like

<p class='myElement'>Hello, World!</p>

I use .append() to add new element to an existing one. E.g.

$('.myElement').append($('<span>Inner Element!</span>'));

Which results in

<p class='myElement'><span>Inner Element!</span></p>

The reason I use .append() is that it allows me to use jQuery to build on the new element. E.g.

var newElement = $('<span>Inner Element!</span>').click(function(e){ alert("Hello!"); });
$('.myElement').append(newElement);

Upvotes: 1

gdoron
gdoron

Reputation: 150253

  1. With .html you override the content, while with .append you add the content to the end of tag.
  2. html accepts a raw string only, with append you can using jQuery object as well.

Example:

$('#foo').html($('<input>')); //invalid!
$('#foo').append($('<input>')); //Valid!

With events:

var $input = $('<input>').click(function(){
    alert('foo');
});

$('#foo').append($input); 

Upvotes: 2

Related Questions