.html()
.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()
Parameters
None
Return value
A string containing the HTML representation of the element.
Description
Get the HTML contents of the first element in the set of matched elements.
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
Return value
The jQuery object, for chaining purposes.
The following example both gets and sets HTML content of a div tag:
<!DOCTYPE html>
<html>
<head>
<script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js">
</script>
<script>
$(function(){
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.
This allows for dynamic creation of content, instead of just static text.
<!DOCTYPE html>
<html>
<head>
<script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js">
</script>
<script>
$(function(){
$("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>
Set value for <p>
<html>
<head>
<script src="http://java2s.com/Book/JavaScriptDemo/jQuery/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("p").html("<b>bold</b>");
$("p b").append(document.createTextNode("added")).css("color", "red");
});
</script>
</head>
<body>
<body>
<p>asdf</p>
</body>
</html>
Home
JavaScript Book
jQuery
JavaScript Book
jQuery
DOM:
- jQuery DOM
- $("html tags"):generate code with the jQuery wrapper function.
- .add()
- .addClass()
- .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()
- .position()
- .prepend()
- .prependTo()
- .prev()
- .prevAll()
- .prevUntil()
- .remove()
- .removeClass()
- .removeAttr()
- .replaceAll()
- .replaceWith()
- .siblings()
- .scrollLeft()
- .scrollTop()
- .slice()
- .text()
- .toArray()
- .toggleClass()
- .unwrap()
- .val()
- .wrap()
- .wrapAll()
- .wrapInner()
- .width()