How to create text input dynamically with JavaScript?

We can create a text input dynamically with JavaScript by creating an <input> element and then appending it to the desired parent element in the DOM.

For example, we:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamically Create Text Input</title>
</head>
<body>

<div id="container">
  <!-- Text inputs will be added here -->
</div>

<button onclick="addTextInput()">Add Text Input</button>

<script>
function addTextInput() {
  // Create a new input element
  var input = document.createElement("input");
  // Set the type attribute to "text"
  input.type = "text";
  // Optionally, set other attributes such as id, name, placeholder, etc.
  input.placeholder = "Enter your text...";
  
  // Get the parent container where you want to append the input
  var container = document.getElementById("container");
  // Append the input element to the container
  container.appendChild(input);
}
</script>

</body>
</html>

In this example, clicking the “Add Text Input” button triggers the addTextInput() function, which dynamically creates a new <input> element with a type of “text” and a placeholder attribute.

Then, it appends the input element to the <div> element with the id “container”.

We can adjust this code to suit our specific requirements, such as setting other attributes or adding event listeners to the dynamically created input elements.