00 Votes

JavaScript and jQuery: Replace content of an element by using innerHTML

Tutorial by Progger99 | 2011-12-27 at 11:36

In this little mini tutorial I want to show you, how to replace the inner of an element in HTML with JavaScript and jQuery with any other new content.

Let's assume, that we have an element, for example this DIV here, that we have named with the id "test":

<div id="test">Old Content</div>

Now we want to replace the content of this element with the string "Hello World". For this, we want to look at a solution with JavaScript and another solution with jQuery.

The JavaScript Solution

document.getElementById("test").innerHTML = "Hello World";

In JavaScript, we can use the function getElementById() to select our element and to replace its content with "Hello World" like it is shown in the example.

The jQuery Solution

$("#test").html("Hello World");

Easier it will be, if we are using jQuery. Here it is sufficient to select our element with $("#test") and to use the function html() to change the innerHTML of the element.

ReplyPositiveNegative

About the Author

AvatarThe author has not added a profile short description yet.
Show Profile

 

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.