Please explain to me why and why in this problem I get the parent of the button?

Dan input. Next to it is a button "+". By clicking on this button, another empty input should appear below our input.

var button = document.getElementById('button'); button.addEventListener('click', func); function func() { var parent = button.parentElement; var newInput = document.createElement('input'); parent.appendChild(newInput); } 
 <input type="submit" value="+" id="button"> <input type="text"> 

  • 3
    How to find out on which element to add an input? Answer: the one that is the button. What element is the button on? Answer: on the parent - Andrio Skur
  • one
    <input type = "submit" value = "+" id = "button"> Very doubtful. Submit is not needed for this. - Hikikomori

2 answers 2

var parent = button.parentElement; ?????? (parentElement) <--- For this, of course. parentElement selects the parent element.

 var button = document.getElementById('button'); button.addEventListener('click', func); function func() { var parent = document.getElementById('my-bl'); var newInput = document.createElement('input'); parent.appendChild(newInput); } <div id="my-bl"> <button id="button">+</button> <input type="text"> </div> 
  • Read the question again carefully. - Hikikomori
  • AppendChild appends to the end of the selected block. Choose a genus. block and make appendChild and all! - GRozny
  • If you do not select a specific block, it does not know where to add it. And your unit is a kind here. block. Clear? - GRozny

Please explain to me why and why in this problem I get the parent of the button?

You need to know where to add "children", in this case, who, if not the parent element, knows their children.

 var button = document.getElementById('button'); button.addEventListener('click', func); function func() { var parent = button.parentElement; console.log(parent.tagName); //Body var newInput = document.createElement('input'); parent.appendChild(newInput); } 
 <input type="submit" value="+" id="button"> <input type="text"> 

Doc parentNode