The getElementsByTagName()
method returns a
collection of all elements with the specified tagname as a NodeList object.
getElementsByTagName |
Yes | Yes | Yes | Yes | Yes |
document.getElementsByTagName(tagname)
Parameter | Type | Description |
---|---|---|
tagname | String | Required. The tagname of the elements to return |
A NodeList object.
The following code shows how to get all elements with the specified tag name.
<!DOCTYPE html>
<html>
<body>
<p>An unordered list:</p>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul><!--from ww w.j a v a 2 s . c o m-->
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("LI");
document.getElementById("demo").innerHTML = x[1].innerHTML;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to find out how many <li> elements in the document.
<!DOCTYPE html>
<html>
<body>
<!-- w w w . j ava 2s. c om-->
<p>An unordered list:</p>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("LI");
document.getElementById("demo").innerHTML = x.length;
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to change the text of the first <p> element (index 0) in the document.
<!DOCTYPE html>
<html>
<body>
<p>This is also a paragraph.</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w ww . j av a 2 s . c om-->
document.getElementsByTagName("P")[0].innerHTML = "Hello World!";
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to change the background color of all <p> elements.
<!DOCTYPE html>
<html>
<body>
<p>This is a p element</p>
<p>This is also a p element.</p>
<button onclick="myFunction()">test</button>
<script>
function myFunction() {<!--from w ww. j av a 2 s. c o m-->
var x = document.getElementsByTagName("P");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.backgroundColor = "red";
}
}
</script>
</body>
</html>
The code above is rendered as follows:
The following code shows how to use the "*" parameter.
<!DOCTYPE html>
<html>
<body>
<!--from w w w . j a va 2 s . com-->
<p>An unordered list:</p>
<ul>
<li>A</li>
<li>B</li>
<li>C</li>
</ul>
<button onclick="myFunction()">test</button>
<p id="demo"></p>
<script>
function myFunction() {
var x = document.getElementsByTagName("*");
document.getElementById("demo").innerHTML = x[3].innerHTML;
}
</script>
</body>
</html>
The code above is rendered as follows: