How to use getElementsByTagName In Javascript
This method selects elements based on their tag name. It returns a collection of elements with the specified tag name.
Syntax:
document.getElementsByTagName('tag')
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>getElementsByTagName Example</title>
</head>
<body>
<p>Thanks for visiting GFG</p>
<p>This is showing how to select DOM element using tag name</p>
<script>
const paragraphs = document.getElementsByTagName('p');
paragraphs[0].style.color = "green";
paragraphs[1].style.color = "blue";
paragraphs[0].style.fontSize = "25px";
paragraphs[0].style.textAlign = "center";
paragraphs[1].style.textAlign = "center";
paragraphs[0].style.marginTop = "60px";
</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