Using the Get Element By Id method in JavaScript

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. The syntax of the method looks like:

 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 will need to brush up on your HTML knowledge now. The paragraph example below contains an onclick event which runs the ‘change’ function to replace the paragraph text using the innerHTML method.

The innerHTML method is used to replace the content of an HTML element such as a paragraph by referring to the element’s ID.

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

This is what the code looks like. There are also some examples of HTML elements/tags being used to format a pagraph with bold/underlined/italic text and a large heading. Notice that when you click on these paragraphs and headings, the text does not change. Only the paragraph with the ID ‘paragraph’ will change its text when it is clicked.

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="utf-8"/>
 <title>JavaScript - Referencing elements</title>
 <script type="text/javascript">
 
 /* 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.
 The syntax is: document.getElementById('id goes here')
 In the example below, it looks for the paragraph element ID.
 If you're not familiar with HTML elements (tags) and IDs such as <p>, <h1>, etc. then you will need
 to brush up on your HTML knowledge now.
 The paragraph example below contains an onclick event which runs the 'change' function to replace the
 paragraph text.
 */ 
 
 function change(){
 var paragraph = document.getElementById('paragraph');
 paragraph.innerHTML = "You clicked here.";
 // innerHTML refers to what is inside the > < tags in the paragraph element which in this example
 // is the words "Click me".
 }
 
 
 </script>
 
</head>
<body>
<p>This is a regular paragraph.</p>
<p>This is another paragraph with <b>bold</b>, <u>underlined</u>, and <i>italic text</i>.</p>
<h1>This is a heading</h1>
 
<p id="paragraph" onclick="change();">Click me</p>
 
</body>
</html>

 

Next tutorial: Changing an image using the getElementById() method