In JavaScript, you can select HTML elements by their tag names using the getElementsByTagName
method. Here is an example:
<!DOCTYPE html>
<html>
<head>
<title>Select elements by tag name</title>
<script>
window.onload = function () {
var elements = document.getElementsByTagName("p");
for (var i = 0; i < elements.length; i++) {
elements[i].style.color = "red";
}
};
</script>
</head>
<body>
<h1>Heading</h1>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p>Yet, another paragraph.</p>
</body>
</html>
In the above example, the JavaScript code selects all the <p>
elements in the HTML document and changes their color to red.