document.getElementById() method
The getElementById() method returns the element that has the ID attribute with the specified value.
This method is one of the most common methods in the HTML DOM, and is used almost every time you want to manipulate, or get info from, an element on your document.
it will Returns null if no elements with the specified ID exists.
An ID should be unique within a page. However, if more than one element with the specified ID exists, the getElementById() method returns the first element matched with specified ID.
<!DOCTYPE html>
<html> <body> <p id="demo_GetElementbyId">Click to change the text</p> <button onclick="myFunction()">Click it</button> <script> function myFunction() { document.getElementById("demo_GetElementbyId").innerHTML = "Hello World....."; } </script> </body> </html> |
Output is
<!DOCTYPE html>
<html> <body> <p id="demo_GetElementById">Click the button to change the color of text.</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var x = document.getElementById("demo_GetElementById"); x.style.color = "green"; } </script> </body> </html> |
Output is :-