.html()
Description
.html()
gets or sets a value
depending on whether you feed it an argument.
.text()
works with both XML and HTML
documents, .html()
doesn't.
.text()
gets the text contents of
all descendants, whereas .html()
retrieves only the first element matched.
Syntax for .html() (getter)
.html()
gets the HTML contents of the first element in the set of matched elements.
Its return value is a string containing the HTML representation of the element.
Syntax for .html() (setter)
.html(htmlString)
htmlString: A string of HTML to set as the content of each matched element.html(function)
function: A function returning the HTML content to set
Its return value is the jQuery object, for chaining purposes.
Set and get HTML content
The following example both gets and sets HTML content of a div
tag:
<!DOCTYPE html>
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js">
</script>
<script>
$(function(){<!-- w ww.j a v a2 s .com-->
var content = $("div").html();
document.writeln(content);
$("div").html("<p style='color:red;'>RED</p>");
});
</script>
</head>
<body>
<div>
<ul>
</ul>
</div>
</body>
</html>
Both .text()
and .html()
also accept a function as a parameter for setting content.
The code above generates the following result.
Use function to create content dynamically
This allows for dynamic creation of content, instead of just static text.
<!DOCTYPE html>
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js">
</script>
<script>
$(function(){<!--from w w w. j av a2s. c o m-->
$("div#testHTML").html(function(){
var content = "";
for(i = 1; i <=3; i++){
content += "testing " + i + "...<br />";
}
return content;
});
});
</script>
</head>
<body>
<div id="testHTML">
</div>
</body>
</html>
The code above generates the following result.
Set paragraph content and apply style
The following code sets content for a paragraph and
then set color value for <p>
.
<html>
<head>
<script src="http://java2s.com/style/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){<!--from w ww . java2 s.c o m-->
$("p").html("<b>bold</b>");
$("p b").append(document.createTextNode("added")).css("color", "red");
});
</script>
</head>
<body>
<body>
<p>java2s.com</p>
</body>
</html>
The code above generates the following result.
.after()
.andSelf()
.append()
.appendTo()
.attr()
.before()
.children()
.clone()
.closest()
.contents()
.css()
.detach()
.filter()
.first()
.get()
.has()
.hasClass()
.height()
.html()
.index().innerHeight()
.innerWidth()
.insertAfter()
.insertBefore()
.is()
.last()
.map()
.next()
.nextAll()
.nextUntil()
.not()
.offset()
.offsetParent()
.outerHeight()
.outerWidth()
.parent()
.parents()
.parentsUntil()
...