jQuery

jQuery innerHTML Examples

If you have heard about jQuery innerHTML, then at some point of time or other, you must have wondered how to use jQuery to replace innerHTML of Div. In this article, I am going to share some examples on how to do just that.

Examples for using  jQuery to Replace innerHTML of Div

Here is an example with complete source code that shows how to use jQuery to replace innerHTML of Div. The example assumes that there is a div with ID “my_div” with some default content and this content will need to be replaced with other text. Similarly, the content of the div with class “my_div2” gets replaced with replacement text.  All this happens when a button is clicked.

Example: Here is the complete source code to replace innerHTML of div using jQuery

<html>
<head>
<title>Replace innerHTML of Div using jQuery</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
</head>

<body>

<div id="my_div">Default content</div>

<div class="my_div2">Default content 2</div>

<input type="submit" name="replace" id="replace" value="Replace" />

<script type="text/javascript" language="javascript" >

$('#replace').click(function() {

	//Using ID
	$("#my_div").html("This is replacement text.");

	//Using Class
	$(".my_div2").html("This is replacement text 2.");

});

</script>

</body>
</html>

When you run the above code, simply click on the button and you will see that the default text “Default content” is changed to “This is replacement text.”. Similarly, the default text “Default content 2” is changed to “This is replacement text 2.”

Simple, isn’t it?

Do you know of any other ways to replace innerHTML of Div using jQuery? Feel free to suggest by commenting below.

Share your thoughts, comment below now!

*

*