Using the GetElementById() method in JavaScript

The getElementById() 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.

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

Sample HTML Code (index.html):

<html>
    <head>
        <title>Using the document.getElementById() method</title>
        <script src="script.js"></script>
    </head>

    <body>
        <p id="mytext" onclick="changeText();">Click me!</p>
        
        <input id="mytextbox" type="text">
    </body>
</html>

Sample JavaScript code (script.js):

function changeText(){
    var mytext = document.getElementById('mytext');
    mytext.innerHTML = "You clicked here!";
    mytext.style.color = "green";

    var mytextbox = document.getElementById('mytextbox');
    console.log(mytextbox.value);
}

Next tutorial: Using the getElementsByClassName() method