jQuery API

.html()

Contents:

.html() Returns: String

Description: Get the HTML contents of the first element in the set of matched elements.

  • version added: 1.0.html()

This method is not available on XML documents.

In an HTML document, .html() can be used to get the contents of any element. If the selector expression matches more than one element, only the first match will have its HTML content returned. Consider this code:

$('div.demo-container').html();

In order for the following <div>'s content to be retrieved, it would have to be the first one with class="demo-container" in the document:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>

The result would look like this:

<div class="demo-box">Demonstration Box</div>

This method uses the browser's innerHTML property. Some browsers may not return HTML that exactly replicates the HTML source in an original document. For example, Internet Explorer sometimes leaves off the quotes around attribute values if they contain only alphanumeric characters.

Example:

Click a paragraph to convert it from html to text.

<!DOCTYPE html>
<html>
<head>
  <style>
  p { margin:8px; font-size:20px; color:blue; 
      cursor:pointer; }
  b { text-decoration:underline; }
  button { cursor:pointer; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <p>

    <b>Click</b> to change the <span id="tag">html</span>
  </p>
  <p>

    to a <span id="text">text</span> node.
  </p>
  <p>
    This <button name="nada">button</button> does nothing.
  </p>
<script>
    $("p").click(function () {
      var htmlStr = $(this).html();
      $(this).text(htmlStr);
    });
</script>

</body>
</html>

Demo:

.html( htmlString ) Returns: jQuery

Description: Set the HTML contents of each element in the set of matched elements.

  • version added: 1.0.html( htmlString )

    htmlStringA string of HTML to set as the content of each matched element.

  • version added: 1.4.html( function(index, oldhtml) )

    function(index, oldhtml)A function returning the HTML content to set. Receives the index position of the element in the set and the old HTML value as arguments. jQuery empties the element before calling the function; use the oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set.

The .html() method is not available in XML documents.

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

<div class="demo-container">
  <div class="demo-box">Demonstration Box</div>
</div>

The content of <div class="demo-container"> can be set like this:

$('div.demo-container')
  .html('<p>All new content. <em>You bet!</em></p>');

That line of code will replace everything inside <div class="demo-container">:

<div class="demo-container">
  <p>All new content. <em>You bet!</em></p>
</div>

As of jQuery 1.4, the .html() method allows the HTML content to be set by passing in a function.

$('div.demo-container').html(function() {
  var emph = '<em>' + $('p').length + ' paragraphs!</em>';
  return '<p>All new content for ' + emph + '</p>';
});

Given a document with six paragraphs, this example will set the HTML of <div class="demo-container"> to <p>All new content for <em>6 paragraphs!</em></p>.

This method uses the browser's innerHTML property. Some browsers may not generate a DOM that exactly replicates the HTML source provided. For example, Internet Explorer prior to version 8 will convert all href properties on links to absolute URLs, and Internet Explorer prior to version 9 will not correctly handle HTML5 elements without the addition of a separate compatibility layer.

Examples:

Example: Add some html to each div.

<!DOCTYPE html>
<html>
<head>
  <style>

  .red { color:red; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <span>Hello</span>
  <div></div>
  <div></div>
  <div></div>
<script>$("div").html("<span class='red'>Hello <b>Again</b></span>");</script>

</body>
</html>

Demo:

Example: Add some html to each div then immediately do further manipulations to the inserted html.

<!DOCTYPE html>
<html>
<head>
  <style>
  div { color:blue; font-size:18px; }
  </style>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <div></div>
  <div></div>
  <div></div>
<script>

    $("div").html("<b>Wow!</b> Such excitement...");
    $("div b").append(document.createTextNode("!!!"))
              .css("color", "red");

</script>

</body>
</html>

Demo:

Support and Contributions

Need help with .html() or have a question about it? Visit the jQuery Forum or the #jquery channel on irc.freenode.net.

Think you've discovered a jQuery bug related to .html()? Report it to the jQuery core team.

Found a problem with this documentation? Report it to the jQuery API team.

* All fields are required
  • Ashish

    Is the form tag removed while setting the dom element html ?
    say x = …
    then some_element.html(x) is removing the form tag from the “Set” html. Any ideas ?

  • Ashish

    Well…found the issue…
    In 1.4.1, jquery keeps the DOM HTML compliant.
    So no more dynamic loading of form elements inside form elements.
    I see the rationale behind this but then it will require a bit of rework to change functionality which was built up on jQuery 1.3.2

  • Anonymous

    What happens to the events attached to the DOM elements which were replaced by using html(SomeContent)? Are they also removed from memory? If yes, is this also applicable on IE-6?

  • Pipeman

    Is there a jQuery equivalent of outerHTML? Seen workarounds like:
    var html = $(”).append(target.clone()).remove().html();

    here:
    http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html

  • Anonymous

    I have tried using .html() to set the values of certain divs. When I insert a string directly, it works however if I pass in a string variable, it does not set the value correctly. Does anyone know how to get .html() to work with variable parameters?

    Edit: The problem may be that the string did not have any html inside of it. When I had a variable that contained some html wrapped in a div tag, the div updated correctly.

  • MattMatt

    You wouldn’t mind sharing the code you used to get the variable would ya?

  • Anonymous

    Sure here is an example
    var strPercentDone = “100%”;
    $(“#lblPercentDone”).html(strPercentDone);

    In my actual code I had the string set to a function call that would return a string, but for some reason even this test did not work properly. It could be the way my site is designed, I am not sure. Later when I did this and I had a div tag inside the variable, it posted html just fine.

  • namehere

    I used to pass data containing JavaScript in tag to html() and then to use eval() to execute them. worked fine with jQuery 1.3.2, not working with 1.4.2

    Is this some kind of a precautions feature in new release or a bug? and what is the best way to pass variables width data from backend to frontend after using ajax query, so I could manipulate them as i want. JSON? Can someone give me a link describing how to do that?

    /xcjuz my lame English/

  • namehere

    I guess i figured it out. I can eval() simple JS, but jQuery escapes all jQuery. and $. functions, so they are not executed anymore…

    Can somebody confirm this? And advise me the best way to manipulate data and execute JS after ajax request?

    thanks

  • Jesús Ángel

    Hi!

    Did you find any workarround to inject JQuery code with this method?

    Thanks

  • namehere

    well, you can change the source code of jQuery to get rid of the function stripping the code. OR you can use alternative marking fo jQuery functions and then replace them on successful result before doing eval()

    but neither seem to be a reasonable solution… :)

    Personally i use JSON to pass all data i need and on a successful AJAX result just call jquery functions

  • Jesús Ángel

    Thanks for your reply.

    I had an error in my code. The html() method strips the javascript, but the code is executed which is what I need.

  • samarties

    have you tried using $(“#element”).get(0).outerHTML;

    I think this works?

  • samarties

    just tested in Chrome and IE 7 & 8 and it works, but it didn’t work in FF 3.6, anyone know why?

  • http://david.olrik.dk David Jack Wange Olrik

    You can use .replaceWith(); instead of .html(); as replaceWith(); will eval your script blocks without escaping them.

    replaceWith() will remove the old element, and put your loaded data in its place.

  • http://twitter.com/matiaslarsson Matias Larsson

    I believe outerHTML is a non standard Microsoft property (http://tinyurl.com/y9nnewq) and not available in all browsers as you've noticed. Try this instead: http://ivorycity.com/blog/2009/08/18/3/

  • tannaz

    hi plz tel me how can use the Replacewith();
    do u have a sample code
    i need this for delete Old Html component(HiddenFild)
    thanks

  • http://david.olrik.dk/ David Jack Wange Olrik

    If you have events attached to the element, you need to switch the data around a bit like so:

    // The new data we want to replace with
    var data = “Stuff”;

    // The element we want to replace
    var selector = “#the_id_of_the_element_we_want_to_replace”;

    // Replace old element with the new data, this will remove the
    // old from the dom and add the new one. Any script blocks in the
    // new will be executed.
    var old = $(selector).replaceWith(data);
    // Next we replace the contents of the old element with the contents
    // of the new element.
    $(old).html( $(selector).contents() );
    // The old element now has the new data and looks just like we want
    // it to, and it still has all its events attached. So now all we
    // need to do is move it back
    $(selector).replaceWith(old);

    If you have no events attached to the element you can just do this:
    $(selector).replaceWith(data);

  • http://twitter.com/WoWMottie Mot

    I just wanted to add an example of how to use a function inside of HTML

    $(‘.selector’).html(function(index, html){
    return html.replace(/foo/g,”bar”);
    })

    I always seem to forget to add the “return” in there, so I thought I’d share :)

  • http://nixova.com Nishchay Sharma

    Hey friends, I have some problem here.
    Suppose I load a page using AJAX like this :
    $.get('anime.php',function(data){//Some action});
    And I want the html of a div with some id (say nks) from the response text “data”, then what should I try?
    I tried :
    var x=$(data+” #nks”).html();
    But it din't work.
    Please suggest something.

  • http://twitter.com/jonscottclark Jon Clark

    I just ran into this exact issue. Instead of using .html(data), I used .empty().append(data) and it achieves the desired effect.

  • boodle

    you could try context:

    var x = $('#nks',$(data)).html();

  • Jperez222

    why don't you just try “load” … load(url,parameters,callback)
    $('#myDiv').load('resource.php');

    This will populate myDiv with HTML received from resource.

    if “parameters” is not present GET will be used, otherwise POST will be used (see also serialize() )

  • Hu_cool

    just have a look~~

  • Stevewa

    why this doesn’t work :
    $(‘#title’).children(‘img’).html()

    it’s show me an empty string

  • Peter

    outerHTML is not standard and may not be available in browsers other than IE.

  • kox

    .html() get the first child code of selected element I think.
    tag doesn’t have child code so you can’t get any code.
    If you can wrap the , you can get .

    $(“#title img”).parent().html();

  • Andrew Bessa

    Any way to tell if an html injection is complete?

    $(‘some selecter’).html( longhtmlcode );
    $(‘select item in longhtmlcode’).something();

    The problem I have, is that about every 1 in 15 page loads, the code from the html() function is not ready and the selectors below cannot find the items I injected.

  • JiDW

    Try $(‘some selecter’).html( longhtmlcode ).find(‘select item’).something();

  • Johan

    Hello everybody

    I have a small problem using .html() when I use it on my element. It doesn’t work when there is element inside. Has anyone a idea to fix this problem?

    Chears Johan

  • http://www.learningjquery.com/ Karl Swedberg

    Having a <ul> inside a paragraph is not valid HTML, so all bets are off.

  • http://www.learningjquery.com/ Karl Swedberg

    Having a <ul> inside a paragraph is not valid HTML, so all bets are off.

  • Lujushaw

    Hi,
    I am facing a prob while using html() multiple times in a page. The page contains several $.ajax cals which internally uses html() method to set the innerHTML to some DIVs on Success. Actual problem here is a serious performance hit as all the DIVs(which has been already set by the html() calls) waits for the last html() set operation,Before loading its new innerHTML . Is thr a any reason for this?? orIt is like only after all the $.ajax() calls be completed the browser starts processing these DIVs whose innerHTML is changed.??

  • rpbs

    hi everyone, what's the difference among html() and append() ?

    let's supposed that you have a html content and you have to set it in a <div>.

    i didnt see any differences both doing well…</div>

  • PandemoniumX101

    append adds, whereas html sets.

    So.. if you have some script:
    $(“p”).append(“hello”);
    $(“p”).append(” world”);

    p will have “hello world”

    but if you use html, it will just be world.

    I think.

  • Prym

    You are right :)

  • Prym

    You are right :)

  • JayStar

    @PandemoniumX101 You’re right.
    .append() would add “hello”, then ” world” to p
    .html() would change replace the contents of p with “hello”, and then replace the contents again with ” world”

  • Karthik

    Hi ,
    i m trying to set a content to div using ajax and html() method,but the repeated call makes the content appended to the previous output ,its not overwritten.my code is like this
    $('#cart').html(data)

  • Jiho

    html() returns the content so whenever I need the whole element, I have to:

    wrap(“<div>”).parent().html()

    Isn't it about time we got outerHtml() or something like that?</div>

  • Charlie Sheather

    Hi all, anyone know if this code can be smaller:

    The following is what I have and works perfectly.
    $(“#selectionWrap”).html(document.getElementById('freightDeliveryDummy').innerHTML + “<div id=”"contentWrap”"></div>”);

    But…

    I was wondering if its possible to do something like this:
    $(“#selectionWrap”).html($(“#freightDeliveryDummy”).html + “<div id=”"contentWrap”"></div>”);

    I tried that code, didn't work obviously. If something like that is possible what is the correct syntax for replacement html.

    Cheers
    Charlie

  • Siddhartha_Moitra

    hi,
    I am trying to insert an HTML into a <div> defined using $('#SearchResults').html(data);
    The SearchResults is the id of a div I have declared.
    This works in Mozilla but does not work in IE.
    Any suggestions??
    Sid</div>

  • Curtis V. Schleich

    I don't know if you have already gotten your answer, but the thing most likely causing you issues is the asynchronous nature of $.ajax(). Try adding async: false to your .ajax options to get the behavior that it sounds like you're expecting.

  • http://crashplan.probackup.nl/ Pro Backup

    Goal was to generate a cross browser identical MD5 hash of a long text part of an UTF-8 encoded xhtml document. Not all not md5 output values were identical. I think that is not the fault of jQuery. Copy and paste text from different browsers into a text editor and the results are all different.

    Solution was to use the .html() method instead of .text(), replace all tags and space characters by a space, remove the double spaces, trim it, and finally hash it.

    md5(jQuery.trim($(“#md5″).html().replace(/(]+>|s| )/gi,” “).replace(/ss+/g,” “)))

    This gives an identical md5 hash value at least in Chrome 6, Opera 10.5, Internet Explorer 8, Firefox 3.6 and Safari 5. See for yourself at the bottom of http://crashplan.probackup.nl/remote-backup/terms-and-conditions.en.html

    Caveat#1 As   is the only html entity used in our sample, it could be replaced in one regex together with space characters. When using more html encoded entities you might need a decoder like http://stackoverflow.com/questions/1147359/jquery-decode-html-entities
    Caveat#2 The regex used to match tags is a simplistic one, it might fail in some cases. See http://haacked.com/archive/2004/10/25/usingregularexpressionstomatchhtml.aspx

  • http://rincefire.livejournal.com/ rincefire

    I wonder why does HTML inserted by this function doesn't appear to have some properties.
    For instance, after using
    jQuery('.some-div-class').html(some_html);
    jQuery('.some-div-class').width() returns zero, while said div is displayed as it should.
    class is unique, and selector works just fine, i know it because
    jQuery('.some-div-class').css('left', jQuery('.some-div-class').width()+100) sets position of a said element to 100.

    Has anyone else encountered this?

  • sunco

    Using the printArea plugin i see that it uses the .html() property. I modify it to accept multiple div's and it works fine. The problem comes when some div contains an object, the flashvars dissapear (<param name=”flashvars” value=”…”>)

    Can somebody confirm this please ?

  • Myadmission08

    clear the div before u add.

  • Jarysnet

    Hello. I have problem with .html(). I am using it to generate a new content into existing DIV id=”blabla”. Content is replaced correctly, but in this new content i have in <form> tag <input ….=”" id=”test” type=”button”> tag and in separate js file click(function(){}) method which isnt running after I click on button. Syntax is OK, i am sure. But why the method click() never run by calling from innerHTML content ?? BTW In new html content i am not defining any new javascript file, I am using only one js file defined in HEAD tags of HTML page. </form>

  • http://www.learningjquery.com/ Karl Swedberg

    Can you please post your question to the appropriate forum at http://forum.jquery.com/ ?

    thanks!

  • http://www.learningjquery.com/ Karl Swedberg

    If the element isn't in the DOM at the time you bind the event, it won't run on that DOM element. This is a frequently asked question:

    http://bit.ly/cPBa0x

    In the future, please direct such support requests to the appropriate forum at http://forum.jquery.com/ You'll have a much better chance of having the questions answered there.

  • http://pulse.yahoo.com/_5XGECD6PHP7V556LYOXDV6DB34 Neil M

    Also, if you are trying to add html that contains SCRIPT elements, these elements will be stripped from the resulting html. Not sure if this is the browser's rendering or if it's jQuery, but either way, I see it as being a protective layer against script injection.

  • http://darlesson.com/jquery/ Dee

    You can use $(“<div>”).outerHTML() from this plugin: http://darlesson.com/jquery/outerhtml/. It will also allow you to replace the element itself in the HTML and in the jQuery chaining being, in some cases, more useful than replaceWith().</div>

  • Vinicius Silva Paiva

    Someone know how to get the script element wihing the result html? I really need to make this happen.

  • Renso

    $('#cart').empty().html(data)

  • Renso

    Chain it: $(‘some selecter’).html( longhtmlcode ).something();

  • Rvelosoo

    why on earth is the html() function automatically decoding htmlentities!? It should copy the html verbatim as it is in the dom. when i pass © through the function it gives me the copyright sign, yaiks..

  • TeMc

    This is a rather complicated way and ineffecient.
    Simply do jQuery( whatever )[0].outerHTML;

    Eventhough we're in jQuery, the true javascript is still available ;-)

  • http://www.learningjquery.com/ Karl Swedberg

    But outerHTML isn't cross-browser.

  • Mozilla11

    hi,
    I want to remove only text from element not other html tags from element.

    i'm using $(#div).text('');

    but two input tags inside that div also get removed…

  • nestcn

    good!

  • Mattfloors

    i want to change a text in a tag when menu status change

    html—-
    <div id=”navigation”>
    <div id=”button”>menu </div>
    <ul id=”menu”>
    <li>illustration</li>
    <li>graphic</li>
    <li>store</li>
    <li>about me</li>
    </ul>
    </div>
    jquery—-
    $(“#button”).click(function(){
    $(“#menu”).slideToggle(“fast”);
    if(“#menu:hidden”) {
    $(“span#arrow”).html(“downarrow”)
    }
    else {
    $(“span#arrow”).html(“uparrow”)
    }

    });

  • Arun Kumar

    when I add a string enclosed with < or > symbol, this function considers that as a html tag. how to resolve this. Example: $(“#abc”).html(“<a@b.com>”); inserts as <a@b.com></a@b.com>

    Thanks
    Arun Kumar</a@b.com>

  • Jerinaw

    After attaching some event handlers to content in #somediv and then trying to change the innerHTML of #somediv i get the error “TypeError: Cannot read property 'handler' of undefined”

    Example:
    Content in side #somediv has event handlers attached to it. Like fadeIn or toggle.
    If I try to replace the content of that div, $('#somediv').html(' some html content')
    I get an error “TypeError: Cannot read property 'handler' of undefined”

    Why is this? How can I get around this?

  • Jerinaw

    This does not work for me…what am I missing? I still get the error “TypeError: Cannot read property ‘handler’ of undefined”

    var el = ” + someHtml + ”;
    var selector = ‘#mainContent’;

    var old = $(selector).replaceWith( el ); //Errors out right here
    $(old).html($(selector).contents());
    $(selector).replaceWith(old);

  • Luke Maurer

    Does using html() to set an element's innerHTML first clear out data and event handlers from its descendants, as empty() does? I ask this here because it should be answered in the docs (especially as empty() does document its behavior in this way).

  • Luke Maurer

    Does using html() to set an element's innerHTML first clear out data and event handlers from its descendants, as empty() does? I ask this here because it should be answered in the docs (especially as empty() does document its behavior in this way).

  • Ugot2zBkidNme

    Arun would you not just escape the HTML as you are supposed to do >ab.com<

  • Ugot2BkidNme

    My apologies for the first post I did not double escape. &lt;a@b.com&gt;

  • Jd

    kl;ds;kf;

  • http://twitter.com/Elric_StifStig Elric stifler Wamugu

    thanx.really helped

  • http://www.luca.pierobon.name/blog/ Luke

    As far as I know,
    jQuery('.some-div-class')
    will give you a set of matches, even if you have only one node matching that class..
    The catch is probably there: what do you expect to get as the width of a set of nodes? That's probably why .width() returns 0..
    Have you tried selecting one single node? for instance the first:
    jQuery('.some-div-class').first().width()
    Have a nice day!

  • sathishkumar

    $(“#labelid”).html(“firstname is empty”);

    throw error in ie8, ie7

    please help me!