From jQuery JavaScript Library
« Back to Attributes
html( )
Get the html contents (innerHTML) of the first matched element. This property is not available on XML documents (although it will work for XHTML documents).
Examples:| Name | Type |
|---|
Click a paragraph to convert it from html to text.
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("p").click(function () {
var htmlStr = $(this).html();
$(this).text(htmlStr);
});
});
</script>
<style>
p { margin:8px; font-size:20px; color:blue;
cursor:pointer; }
b { text-decoration:underline; }
button { cursor:pointer; }
</style>
</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>
</body>
</html>
html( val )
Set the html contents of every matched element. This property is not available on XML documents (although it will work for XHTML documents).
Arguments:| val | String | |
|---|
| Set the html contents to the specified value. |
Examples:| Name | Type |
|---|
Add some html to each div.
$("div").html("<span class='red'>Hello <b>Again</b></span>");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("div").html("<span class='red'>Hello <b>Again</b></span>");
});
</script>
<style>
.red { color:red; }
</style>
</head>
<body>
<span>Hello</span>
<div></div>
<div></div>
<div></div>
</body>
</html>
Add some html to each div then immediately do further manipulations to the inserted html.
$("div").html("<b>Wow!</b> Such excitement...");
$("div b").append(document.createTextNode("!!!"))
.css("color", "red");
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(document).ready(function(){
$("div").html("<b>Wow!</b> Such excitement...");
$("div b").append(document.createTextNode("!!!"))
.css("color", "red");
});
</script>
<style>
div { color:blue; font-size:18px; }
</style>
</head>
<body>
<div></div>
<div></div>
<div></div>
</body>
</html>