JavaScript getElementsByTagName()

document.getElementsByTagName("*"); // List of all tags.
We can use getElementsByTagName to get total number of tags , number of a particular tag, manage the style of a tag and many more. Let us first start with our code to know total number of tags used in the page. Here is the demo and sample code.
Demo of total number of tags
Here is the source code
<html>
<head>
<title>Demo of getElementByTagName total number of tags in the page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<script type="text/javascript">
function tag_no(){
var x=document.getElementsByTagName("*");
var str = "Total tags : " + x.length;

var x1=document.getElementsByTagName("p"); 
str=str + " <br>Total P tags : " + x1.length;

document.getElementById('msg').innerHTML=str;
}
</script>
</head>
<body>
<br><br>
<p> this is one para</p>
This is simple text without any para 
<p>this is second Para</p>
<div id='msg'></div><br>
<input type=button onclick='tag_no()' value='Calculate'>

</body>
</html>
Demo of total number of <BR> tags
The changes inside function is here
function tag_no(){
var y=document.getElementsByTagName("br");
var str=" BR  tags : " + y.length;
document.getElementById('msg').innerHTML=str;
}
We can manage the property of each tag by this . We will be looping to change the property of all P tags.
Demo of managing property of tags
Here is the source.
<script type="text/javascript">
function tag_no(){
var y=document.getElementsByTagName("p");
for(var i=0;i<y.length;i++){
y[i].style.color = 'red';
}
}
</script>
Change the text of the first <P> element
<html>
<head>
<title>Demo of getElementByTagName total number of tags in the page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">

<script type="text/javascript">
function tag_no(){
document.getElementsByTagName("p")[0].innerHTML = "Welcome to plus2net";
}
</script>

</head>
<body>
<br><br><br>
<p> this is one para</p>
This is simple text without any para 
<p>this is second Para</p>
<div id='msg'></div><br>
<input type=button onclick='tag_no()' value='Update'>

</body>
</html>

document Object getElementsById Last Modified date of the page
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here




    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer