Javascript innerHTML

The innerHTML property can be used to modify your document’s HTML on the fly.

If you want to access the text within a non-input HTML element, then you are going to have to use the innerHTML property instead of value.

When you use innerHTML, you can change the page’s content without refreshing the page. This can make your website feel quicker and more responsive to user input.

The innerHTML property is used along with getElementById within your JavaScript code to refer to an HTML element and change its contents.

Syntax

document.getElementById(‘{ID of element}’).innerHTML = ‘{content}’;

In this syntax example, {ID of element} is the ID of an HTML element and {content} is the new content to go into the element.

Example:

<script type="text/javascript">
function changeText()
{
var userInput = document.getElementById(‘userinput’).value;
document.getElementById(‘replacetxt’).innerHTML = userInput;
}
</script>

<p>Welcome to the site <b id='replacetxt'>Learn web development</b> </p>
<input type='text' id='userinput' value='Enter Text Here' />
<input type='button' onclick='changeText()' value='Change Text'/>

At default it showing ‘Welcome to the site Learn web development’ , after entering any text within text and click button the ‘Learn web development’ value is replaced by text box value.

Display:

Welcome to the site Learn web development


Posted in Javascript