-1

In my code, only button B works. I tried writing the script at the end. Then both buttons work. Why is that so? In what sequence does the code get executed? Does that have anything to do with this issue?

Code

<!DOCTYPE html>
<html>
<head>
 <title>finding elements</title>
 <script type="text/javascript">
  var x=document.getElementsByTagName("p");
  var y=document.getElementById("d1");
  var z=y.getElementsByTagName("p");
 </script>
 
</head>

<body>
<p id="a1">Hello World</p><br>
<p id="hh">dude it works</p>
<div id="d1">
 <p>Hey man 1</p>
 <p>Hey man 2</p>
 <p>Hey man 3</p>
</div>
 <form name="b0" method="get">
  <input type="button" name="bb" value="A" onclick=document.write(x[1].innerHTML)>
  <input type="button" name="bc" value="B" onclick=document.write(z[1].innerHTML)>
 </form>
</body>
</html>
Spark Fountain
  • 1,716
  • 11
  • 27
  • After you've fixed the references, clicking on a button kills your page, see https://developer.mozilla.org/en-US/docs/Web/API/Document/write – Teemu Jan 31 '20 at 10:50

1 Answers1

2

Your JS is executing before the actual declaration of html elements. If you move your JS code at the end, your code works.

<!DOCTYPE html>
<html>
<head>
 <title>finding elements</title>
 
</head>

<body>
<p id="a1">Hello World</p><br>
<p id="hh">dude it works</p>
<div id="d1">
 <p>Hey man 1</p>
 <p>Hey man 2</p>
 <p>Hey man 3</p>
</div>
 <form name="b0" method="get">
  <input type="button" name="bb" value="A" onclick=document.write(x[1].innerHTML)>
  <input type="button" name="bc" value="B" onclick=document.write(z[1].innerHTML)>
 </form>
</body>

 <script type="text/javascript">
  var x=document.getElementsByTagName("p");
  var y=document.getElementById("d1");
  var z=y.getElementsByTagName("p");
 </script>
</html>
Umair Khan
  • 1,343
  • 13
  • 27