getElementById() method

Coding with JavaScript

🕑 This lesson will take about 10 minutes

The getElementById() method is a very useful method in JavaScript that you will likely use many times when working with JavaScript on a web page to manipulate or grab information from elements on the page. The method returns the element that has an ID of a value we specify when using the method. It can be used to manipulate the element (eg. change its contents or appearance) or get information from it.

The getElementById() method searches through an entire HTML document and looks for an element with whatever ID we specify as the parameter between the quotation marks. Remember that IDs should be unique and used only once on a page. If you have more than one element with the ID specified, then the method will only return the first element that has that ID on the page. The syntax of the method looks like this:

 document.getElementById('id_goes_here')

In the example below, the getElementById() method looks for a paragraph that has the element ID of ‘paragraph’. If you’re not familiar with HTML elements (tags) and IDs such as <p>, <h1>, etc. then you should brush up on your HTML knowledge now. You can check out the HTML & CSS tutorials for that. The paragraph example below contains an onclick event which calls the ‘changeText()’ function to replace the paragraph text using the innerHTML method and also change the text colour.

The innerHTML method is used to replace the content (what goes between the > and < brackets) of an HTML element such as a paragraph. Eg.

<p>this is the innerHTML</p>

Watch the video below and then scroll down to see the sample code.

Sample HTML & JavaScript code

In the example below, we will use the getElementById() method to access a paragraph element and text input (textbox) element on a web page. We will also get access to the text input’s value property so we can get the ‘username’ value that the user typed into the text input. This input is captured when the user clicks the button by calling the getUsername() function on an onclick event. We will then update the innerHTML of the ‘result’ paragraph element’s to display a message containing the user’s name back to the user.