Javascript Reference - HTML DOM getElementsByTagName() Method








The getElementsByTagName() method returns a collection of an elements's child elements by the specified tagname, as a NodeList object.

Browser Support

getElementsByTagName Yes Yes Yes Yes Yes

Syntax

element.getElementsByTagName(tagname)

Parameter Values

Parameter Type Description
tagname String Required. The tagname of the child elements to get




Return Value

A NodeList object, representing a collection of the element's child elements with the specified tagname.

Example

The following code shows how to change the text of the first list item in a list.


<!DOCTYPE html>
<html>
<body>
<!-- w w w  .ja  v a2  s .  c  o  m-->
<ul>
  <li>A</li>
  <li>B</li>
</ul>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var list = document.getElementsByTagName("UL")[0];
    list.getElementsByTagName("LI")[0].innerHTML = "Milk";
}
</script>

</body>
</html>

The code above is rendered as follows:





Example 2

The following code shows how to get the count of <p> elements inside a <div> element.


<!DOCTYPE html>
<html>
<head>
<style>
div {<!--  w  w w.j a  v  a 2  s . c o  m-->
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <p>A</p>
  <p>B</p>
  <p>C</p>
</div>
<button onclick="myFunction()">test</button>
<p id="demo"></p>

<script>
function myFunction() {
    var x = document.getElementById("myDIV").getElementsByTagName("P");
    document.getElementById("demo").innerHTML = x.length;
}
</script>

</body>
</html>

The code above is rendered as follows:

Example 3

The following code shows how to change the background color of the second <p> element inside a <div> element.


<!DOCTYPE html>
<html>
<head>
<style>
div {<!--from w  ww .  j a v  a  2  s.com-->
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div id="myDIV">
  <p>First p element.</p>
  <p>Second p element.</p>
  <p>Third p element.</p>
</div>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {
    var x = document.getElementById("myDIV");
    x.getElementsByTagName("P")[1].style.backgroundColor = "red";
}
</script>

</body>
</html>

The code above is rendered as follows: