Let’s take a look at an example. Consider the following HTML markup:
<div id="myElement">Hello, World!</div>
<script> var element = document.getElementById("myElement"); console.log(element.id); // Output: "myElement" </script>
The getElementById() method returns a reference to the HTML element with the specified ID. In this example, we store the reference to the element in the variable element. We can then access the ID of the element using the element.id property, which will output “myElement” to the console.
Handling Multiple Elements
Keep in mind that an element’s ID should be unique within the HTML document. If you need to target multiple elements, consider using class attributes and the getElementsByClassName() method instead.