The getElementById
method is a fundamental JavaScript function used to select a single HTML element by its id attribute. It returns the element object representing the element whose id property matches the specified string.
Example Usage:
Let's say you have the following HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script src="script.js"></script>
</body>
</html>
In your script.js
file, you can use getElementById
to select the div
and manipulate it:
const root = document.getElementById("root");
const Heading = document.createElement("h1");
Heading.innerHTML = "Hello World";
root.appendChild(Heading);
When you open your HTML file in a browser, the div
with the id root
will now contain an h1
element with the text "Hello World".
Top comments (0)