How to use getElementById In Javascript
This method selects a single element by its unique ID attribute.
Syntax:
document.getElementById('id')
Example:
<!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>
<h1 id="gfg">w3wiki</h1>
<script>
// styling the h1 tag
const element = document.getElementById('gfg');
element.style.color = "green";
element.style.textAlign = "center";
element.style.margin = "30px";
element.style.fontSize = "30px";
</script>
</body>
</html>
Output:
How to select DOM Elements in JavaScript ?
Selecting DOM (Document Object Model) elements is a fundamental aspect of web development with JavaScript. It allows developers to interact with and manipulate elements on a webpage dynamically. Proper selection of elements is crucial for tasks such as updating content, adding event listeners, or modifying styles.
Below are the approaches to select DOM elements in JavaScript:
Table of Content
- Using getElementById
- Using getElementsByClassName
- Using getElementsByTagName
- Using querySelector
- Using querySelectorAll
Contact Us