.html()
S2C Home « Attributes & Properties « .html()
First element HTML retrieval and matched set HTML setting.
Description
The .html()
method is used to retrieve the HTML contents from the first element within the matched set, or set the HTML content of each element within the matched set.
- The
.html()
method is not available on XML documents unlike the.text()
method which is available on both HTML and XML documents. - Uses the browser's
innerHTML
property. - When setting an element's content using the
.html( htmlString )
signature, existing content is replaced by the new content. - When setting an element's content using the
.html( function(index, oldhtml) )
signature, the existing element is cleared before the function is called. So use theoldhtml
argument to reference the previous content.
Syntax
Signature | Description |
---|---|
.html() | Retrieve the HTML contents from the first element within the matched set. |
.html( htmlString ) | Set the HTML contents of each element within the matched set. |
.html( function(index, oldhtml) ) | A function returning the HTML contents to set. |
Parameters
Parameter | Description | Type |
---|---|---|
htmlString | A string of raw HTML. | HTMLstring |
function(index, oldhtml) | A function.
|
Function |
Return
Retrieving - A String
object.
Setting - A jQuery
object including the updated HTML within the matched set.
.html()
ExampleTop
Retrieve the HTML contents from the first element within the matched set.
In the example below when we press the button we get the HTML contents of the table below which has an id of 'table1' and display them in an alert box.
Table Row 1, Table Data 1 | Table Row 1, Table Data 2 |
Table Row 2, Table Data 1 | Table Row 2, Table Data 2 |
$(function(){
$('#btn5').on('click', function() {
alert($('#table1').html());
});
});
.html( htmlString )
ExamplesTop
Set the HTML contents of each element within the matched set.
In the example below when we press the button we select all 'td' elements within the table with an id of 'testtable2'. We then change the text within each 'td' element..
Table Row 1, Table Data 1 | Table Row 1, Table Data 2 |
Table Row 2, Table Data 1 | Table Row 2, Table Data 2 |
$(function(){
$('#btn6').on('click', function() {
$('.testtable2 td').html('Table data changed');
});
});
.html( function(index, oldhtml) )
ExamplesTop
A function returning the HTML contents to set.
In the example below when we press the button the first time we add a new 'td' element to each table row.
? |
? |
$(function(){
$('#btn7').one('click', function() {
$('.testtable3 tr').html( function(index, oldhtml) {
var newhtml = oldhtml + '<td>' + index + '</td>';
return newhtml;
});
});
});
Related Tutorials
jQuery Basic Tutorials - Lesson 9 - Working With CSS Attributes