Javascript DOM HTML document forms Collection loop

Introduction

Loop through all <form> elements in the document, and output the id of each form:

Click the button to display the name of each form element in the document.

View in separate window

<!DOCTYPE html>
<html>
<body>
<form id="myCarForm">
  Favorite Car: <input type="text" name="fname" value="Javascript">
</form>/*from   w  w  w .  j  a  v a2  s. c o  m*/
<form id="myColorForm">
  Favorite Color: <input type="text" name="favcolor" value="Blue">
</form>
<button type="button" onclick="myFunction()">Test</button>

<p id="demo"></p>

<script>
function myFunction() {
  var x = document.forms;
  var txt = "";
  var i;
  for (i = 0; i < x.length; i++) {
    txt = txt +  x[i].id + "<br>";
  }
  document.getElementById("demo").innerHTML = txt;
}
</script>

</body>
</html>



PreviousNext

Related