Using Javascript document object with getElementById

Updated on 23 Mar 2012,
Published on 26 Jun 2008

Javascript getElementById method can be accessed using the document object of DOM. getElementById method returns the reference to the First HTML element whose Id attribute has the same value that is passed to javascript getElementById method. Document object consists of many other methods like close(), open(), getElementsByName etc but getElementById is most commonly used method that can be utilized more easily in Javascript DOM functionality for generating Dynamic HTML.

JavaScript DOM Examples:

You can see the live samples and examples of JavaScript DOM from the following links:

Syntax for JavaScript getElementById method

The Javascript getElementById takes one parameter as id of the HTML element:

document.getElementById("id")

This method can access the various commonly used properties of HTML elements such as className, style, innerHTML, innerText etc. You can change the values of all these properties dynamically using DOM features of Javascript. You can access the properties of getElementById method as follows:

document.getElementById("id").className = "value";

document.getElementById("id").innerHTML = "text value";

document.getElementById("id").innerText = "text value";

You can use the CSS style properties by using associated style object of getElementById method of document object of Javascript as follows:

document.getElementById("id").style.backgroundColor = "value";

document.getElementById("id").style.color = "value";

Above syntax can be used to change the background color of HTML element and text color of HTML element. It will change the values dynamically, only for the targeted HTML element i.e. for the specified HTML element id value.

Output:

You can see the output of above discussed code from the following link:

JavaScript document.getElementById

Continue to next tutorial: Javascript document getElementsByTagName to learn how to get the collection of HTML elements by Tag names.

0 Responses to "Using Javascript document object with getElementById"
Leave a Comment
* required
* required
* will not be published
* optional
* hint: http://www.example.com
  • Subscribe via Email
  • HIRE EzineASP.Net Developers