Javascript - document.getElementsByTagName() method
The getElementsByTagName() method returns a collection of all elements in the document with the specified tag name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Note: The parametervalue "*" returns all elements in the document.
Note: You can use the length property of the NodeList object to determine the number of elements with the specified tag name, then you can loop through all elements and extract the info you want.
<!DOCTYPE html>
<html>
<body>
<p>An unordered list is given bellow:</p>
<ul>
<li>MCA</li>
<li>BCA</li>
<li>MBA</li>
</ul>
<p>Click the button to display the innerHTML of the third li element (index 2).</p>
<button onclick="myFunction()">Click it</button>
<p id="Demo_P"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("LI");
document.getElementById("Demo_P").innerHTML = x[2].innerHTML;
}
</script>
</body>
</html>
|
And Output will be.
Example 2-
<!DOCTYPE html>
<html>
<head>
<style>
div {
border: 1px solid black;
margin: 5px;
}
</style>
</head>
<body>
<div id="DIV_main">
<p> paragraph element inside div.</p>
<p>second paragraph element inside div.</p>
<p> third paragraph element inside div.</p>
</div>
<p>Click the button to find out how many p elements are there</p>
<button onclick="myFunction()">Try it</button>
<p id="outputdiv"></p>
<script>
function myFunction() {
var x = document.getElementById("DIV_main").getElementsByTagName("P");
document.getElementById("outputdiv").innerHTML = x.length;
}
</script>
</body>
</html>
|
And output will be