Click here to Skip to main content
15,898,371 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
HTML
<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<p>hi</p>
        <p>hello</p>
        <p>hi</p>
        <script>
            var arr = document.getElementsByTagName("p");
            for (var x = 0; x < arr.length; x++) {
                arr[x].innerHTML = "Hi there";
            }
        </script>
	</body>
</html>


What I have tried:

Isn't the length of the array (arr.length) equal to 1, since there's only 1 element "p"? So how does this condition work in this code if x can only be less than the array's length?
Posted
Updated 22-Nov-17 7:43am
v2

Actually there are three p elements. Try

JavaScript
<!DOCTYPE html>
<html>
	<head>
		<title>Page Title</title>
	</head>
	<body>
		<p>hi</p>
        <p>hello</p>
        <p>hi</p>
        <script>
            var arr = document.getElementsByTagName("p");
            for (var x = 0; x < arr.length; x++) {
                arr[x].innerHTML = "Hi there " + arr[x].textContent;
            }
        </script>
	</body>
</html>
 
Share this answer
 
getElementsByTagName("p") gets all <p> elements, and there are three p elements, "hi", "hello" and the second "hi", so arr.length will be 3, so x will loop through 0, 1, then 2, as javascript arrays are accessed on a zero-base so 0 is the first, 2 the third, so it will set the innerHTML of all three elements.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900