jQuery html() Method - CodingTag
×


jQuery html()

0 750

  • This jQuery method is used to fetch and set the content of the selected HTML element.

Related Topics:

jQuery delay
jQuery animate

jQuery html

Syntax:

This method has three different signatures which used to work for different tasks:

$(selector).html() ;

This syntax is used to get the HTML content of selected element. It has no parameter.

$(selector).html(content);

The given syntax of html() method is used to set the content of selected HTML element.

Parameter description:

  • content: This parameter represents the new content which to be set to the given selected element. It is mandatory.
$(selector).html(function(index,currentcontent));

This method is also used to set the content of the selected element by using a user defined function.

Parameter description:

  • function(index,currentcontent): This represents a user defined function which return the new content of the selected HTML element. it is optional.
  • index: This parameter is used to get the index position of the element in the set.
  • currentcontent: This parameter is used to return the current HTML content of the selected element.

Example 1

In this example , we replace the content of the given paragraph.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para1{
background:pink;
padding:20px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".para1").html("This is the new content of the paragraph.");
});
});
</script>
</head>
<body>

<h2> jQuery html() method Example </h2>
<p class="para1"> This is a paragraph. </p>
<button> Click me! </button>

</body>
</html>

Output:

When you click the paragraph,

Example 2

In this example we set the content of a paragraph by getting the content of another paragraph.

<html>
<head>
<title> jQuery Example </title>
<script type = "text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
</script>
<style>
.para1{
background:pink;
padding:20px;
}
.para2{
background:lightgray;
padding:20px;
}
button{
background:green;
padding:10px;
color:white;
border:1px solid green;
}
</style>
<script>
$(document).ready(function(){
$(".para1").click(function(){
$con=$(".para2").html(); //get the content of second paragraph
$(".para1").html($con); // set this content as first paragraph
});
});
</script>
</head>
<body>

<h2> jQuery html() method Example </h2>
<p class="para1"> Change me. </p>
<p class="para2"> Hello friends!! welcome to our tutorial.. </p>
</body>
</html>

Output:

When you click on first paragraph,



Best WordPress Hosting


Share:


Leave a Reply


Comments
    Waiting for your comments