In this shot, we are going to learn about a method that helps find the DOM element so that we can use it to change the element according to our needs.
There are different methods that you can use to get DOM elements. In this shot, we are going to use document.getElementById()
, which returns a DOM element. The element contains different properties that define its behavior. If the method does not find any element in DOM with the specified ID, then it returns null.
var element = document.getElementById('ID');
getElementById(ID)
takes a parameter of type string. ID
is given to an HTML element that is unique for that element. This unique ID helps in searching for the required element in the DOM tree.
In the code below, we assign a unique ID to an element.
<p id="Test"></p>
In the <p>
HTML tag above, we use the id
attribute to assign an ID. IDs are case-sensitive, which means “Test” and “test” are different IDs. Check the code below to get the <p>
element.
//correctvar element = document.getElementById("Test");//wrong "test" should be "Test"var element = document.getElementById("test");
In the code below, we are trying to get the element with ID intro3
, and no element in the HTML page has ID intro3
. After we store the value returned by getElementById
, we use console.log()
to display it on the console. As expected, the output is null.
Now, we will try to use the getElementById()
method to change the color of an element with the click of a button.
The HTML page only has two elements: a paragraph and a button. The task is to change the color of the paragraph element (Hey, Hello) when we click on the button (Click Here!!!).
In JavaScript:
In line 1, we use document.getElementById('test')
to get the element. test
is the ID given to <p>
element. The method returns an object and stores it in a variable named element
.
In line 4, we have a function, change()
, which will be called when we click on the button.
In line 5, we use the element object to change the element property. We use element.style.color
;
element
is the object that has the style property. style
has several properties, one of which is color
.