Using GetElementById Function With InnerHTML Property in JavaScript

This article shows how to use the GetElementById function with the InnerHTML property in ASP.NET using JavaScript. In this article, you will see how to get the id of the HTML element using the GetElementById function and use it with the InnerHTML property. First start Visual Studio .NET and make a new ASP.NET web site using Visual Studio 2010.

GetElementById Function

The getElementById function refers to the HTML element using its ID. The id property sets or returns the id of an element.

  <script type="text/javascript">

        function ShowID() {

            var Getid = document.getElementById('TextMessage');

            alert(Getid.id);

        }      

    </script>

 

Output

 

getlementid-function-in-javascript.jpg

What is  InnerHTML Property?

The InnerHTML property can be used to modify a HTML document. The innerHTML property exists in all types of the major browsers. 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.

Syntax

The syntax for using innerHTML looks like this:

document.getElementById('ID of element').innerHTML = 'Data or content';

getElementById: The getElementById refers to the HTML element using its ID.

Data or content: Data is the new content to go into the element.

JavaScript Code

So to make it work use the following JavaScript function code in your page:

<script type="text/javascript">

     function ShowMessage() {

     document.getElementById('TextMessage').innerHTML = 'C-sharpCorner';

     }      

</script>

 

Now drag and drop a Button Control onto the form such that you have:

 

<input type="button" onclick="ShowMessage()" value="Show Message" />&nbsp;

<p id="TextMessage"></p>

Example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RefreshPage.aspx.cs" Inherits="RefreshPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script type="text/javascript">

        function ShowMessage() {

            document.getElementById('TextMessage').innerHTML = 'C-sharpCorner';

        }      

</script>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <input type="button" onclick="ShowMessage()" value="Show Message" />&nbsp;

    <p id="TextMessage"></p>

    </div>

    </form>

</body>

</html>

 

Output

 

InnerHTML-property-in-javascript.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all