The document method getElementById() returns an element object representing the element whose id property matches with the given value. This method is used to manipulate an element on our document & is widely used in web designing to change the value of any particular element or get a particular element. If the passed ID to the method does not exist then it returns null.
A unique id should be used in the web pages. Although, if there is more than one element for the specific id exist then the only first element will consider & return by getElementByID in the code.
const gfg = document.getElementById(id);
- id: The id of the element which we want to grab. The is a case-sensitive string that is unique within the document.
Return value: An element object with the specified id, or null if no matching element is found.
Example: The below example illustrates the use of getElementById, by getting the element having the id attribute for the specified value.
Output: Here, you can see “GeeksforGeeks” printed in the console tab. Now, after grabbing an element, we can perform any operations on that element like changing text, adding style, etc.