jQuery html() method

Introduction

Change the content of all <p> elements:

View in separate window

<!DOCTYPE html>
<html>
<head>
<script 
 src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>//  w  ww .j  a v a 2 s. c om
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("p").html("Hello <b>world!</b>");
  });
});
</script>
</head>
<body>

<button>Change content of all p elements</button>

<p>This is a paragraph.</p>
<p>This is another paragraph.</p>

</body>
</html>

The html() method sets or gets the content via innerHTML of the selected elements.

As getter, it returns the content of the first matched element.

As setter, it overwrites the content of all matched elements.

Return content:

$(selector).html()

Set content:

$(selector).html(content)

Set content using a function:

$(selector).html(function(index,current_content))
Parameter
Optional
Description
content
Required.
new content for the selected elements
function(index,current_content)


Optional.


sets a function that returns the new content for the selected elements
index - the index position of the element in the set
current_content - the current HTML content of the selected element



PreviousNext

Related