📅  最后修改于: 2023-12-03 15:32:21.657000             🧑  作者: Mango
JS getElementById is a method used in JavaScript to select and retrieve an HTML element by providing its unique ID name.
To use the getElementById method, call it on the document object and provide the unique ID name of the HTML element within the parentheses.
document.getElementById('idName');
For example, consider the following HTML code:
<!DOCTYPE html>
<html>
<head>
<title>JS getElementById Example</title>
</head>
<body>
<h1 id="main-title">Welcome to my website!</h1>
<p id="intro">Learn more about me and what I do</p>
</body>
</html>
To retrieve the H1 element with the ID "main-title," we can use the following JavaScript code:
const title = document.getElementById('main-title');
Now, the title
variable holds a reference to the H1 element with the ID "main-title."
There are several benefits to using the getElementById method in JavaScript:
There are a few caveats to keep in mind when using getElementById:
Overall, getElementById is a powerful and useful method in JavaScript that every programmer should be familiar with. By using this method, you can quickly and easily select HTML elements with unique IDs and manipulate them using other JavaScript methods and events.