WebMasterCampus
WEB DEVELOPER Resources

Javascript getElementsByTagName vs getElementById

Learn the difference between Javascript getElementsByTagName vs getElementById


Javascript getElementsByTagName vs getElementById

We use getElementById to get the reference of an element by referring it’s unique id. If the id we are referring exist we will get the reference. Once we will get the reference we can use it’s methods and properties easily.

Let’s check the following code


<p id="para1"> This is a paragraph. We can use to write passage or information or normal text that we would like to use. </p>

<div id="result"></div>

<script>
	document.getElementById("result").innerHTML = document.getElementById("para1").innerHTML;
</script>

We use getElementsByTagName to get the references of all elements by providing element name or tag name. This method return HTMLCollection of elements with the given tag name. Once we get the reference we can use it’s methods and properties easily.


<p id="para1"> This is a paragraph. We can use to write passage or information or normal text that we would like to use. </p>

<div id="result"></div>

<script>
	document.getElementsByTagName("div")[0].innerHTML = document.getElementById("para1").innerHTML;
</script>
Created with love and passion.