In Javascript, The getElementById method is used to access an HTML element on a web page by its unique identifier, known as the "id" attribute.
This method is part of the Document Object Model (DOM) API, which allows Javascript to interact with the structure and content of an HTML document.
var element = document.getElementById(id);
id: It specifies the `ID` of the HTML element we want to access either to fetch information or modify content.
Return value: If an element with the specified ID exists in the document (DOM), The `getElementById` function returns a reference to that element. Otherwise, it returns null.
The `getElementById` method is used to obtain a reference to the HTML element with the `id` attribute set to 'root'.
Once the reference is obtained, you can manipulate the element by changing its content (innerHTML) or applying styles (style property), among other things.
<div id="root">This is a div element with an id of 'root'.</div> <script> // Accessing the element with id 'root' var element = document.getElementById('root'); // Modifying the content of the element element.innerHTML = 'content changing using JavaScript.'; // Adding a CSS style to the element element.style.color = 'black'; </script>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>getElementById Example</title> </head> <body> <div id="root">This is a div element with an id of 'root'.</div> <script> // Accessing the element with id 'root' var element = document.getElementById('root'); // Modifying the content of the element element.innerHTML = 'content changing using JavaScript.'; // Adding a CSS style to the element element.style.color = 'black'; </script> </body> </html>
In the above example, we have created the element `div` with `id` as `root`.
In the Next Step, Inside the `Script` tag we try to access an element whose `id` is `root`.
In the Next Lines, we modify the `content` and `color` of the element.