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, we can use .html() to get the contents of any element. If the selector expression matches more than one element, only the first one's HTML content is 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.min.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.

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

When we use .html() to set elements' contents, any contents that were in those elements is completely replaced by the new contents. Consider the following HTML:

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

We can set the HTML contents of <div class="demo-container"> like so:

$('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 us to set the HTML content 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>.

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.min.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.min.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:

Comments

  • Support requests, bug reports, and off-topic comments will be deleted without warning.

  • Please do post corrections or additional examples for .html() below. We aim to quickly move corrections into the documentation.
  • If you need help, post at the forums or in the #jquery IRC channel.
  • Report bugs on the bug tracker or the jQuery Forum.
  • Discussions about the API specifically should be addressed in the Developing jQuery Core forum.
  • 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.??
  • Johan
    Hello everybody

    I have a small problem using .html() when I use it on my

    element. It doesn't work when there is

    <ul> element inside. Has anyone a idea to fix this problem?

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

  • 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();
  • kox
    I want to get the HTML code that I selected like a Firebug.
    I wish know that why my code doesn't work.
    Please tell me...

    $('*').click(function(){
    alert(event.target.html());
    });
  • Stevewa
    why this doesn't work :
    $('#title').children('img').html()

    it's show me an empty string
  • kox
    .html() get the first child code of selected element I think.
    <img> tag doesn't have child code so you can't get any code.
    If you can wrap the <img>, you can get <img>.

    $("#title img").parent().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() )

  • 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.
  • waaa, I prefer $.post
  • boodle
    you could try context:

    var x = $('#nks',$(data)).html();
  • 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 :)
  • namehere
    I used to pass data containing JavaScript in <script> 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/</script>
  • 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
  • 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.
  • 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
  • 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 = "<div>Stuff</div>";

    // 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);
  • 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
Time to generate: 1.88565