javascriptdomparent-childchild-nodes

how to add a childNode to an element in javascript


I managed to add an input(text-field of login) childNode to a label(login)

<script>
  let wrapperr = document.getElementById("dynamic-field");

  var label1 = document.createElement("label");
  label1.appendChild(document.createTextNode("login"));
  wrapperr.appendChild(label1);

  linebreak = document.createElement("br");
  label1.appendChild(linebreak);

  var input1 = document.createElement("input");
  label1.insertBefore(input1, label1.children[1]).style.width = "94%";

</script>

now I want to add to that input a childNode of label(password) and to that label another childNote for the password-field.

below is my try

<script>
  var label2 = document.createElement("label");
  label2.appendChild(document.createTextNode("password"));

  line_break.insertBefore(label2, line_break.children[1]).style.width = "94%";
  var input2 = document.createElement("input");

  label2.insertBefore(input2, label2.children[1]).style.width = "94%";
</script>

Solution

  • You can't add a child to a BR element - only to its parent. Doing so, will automatically make it the last child, unless you specifically choose otherwise.