简体   繁体   中英

I have <div> boxes with same class with buttons. On button click a textbox should be added to the respective box

On pressing the second 'Add Task' button, a textbox should be added to the second div, similary with 3rd, 4th How do I refer to particular div element? What I have done below adds textboxes to the first div no matter which button is pressed.

HTML

<body>
    <div id="project">
      LIST IT
    </div>
    <div id="board">
      Java Project
    </div>
  <template id="listTemp">
    <form class="frm" >
      <input type="text" placeholder="Enter list name">
    </form>
    <button type="button" name="task" class="lst btn btn-secondary" onclick="addTask()">Add Task</button>
  </template>
    <button type="button" name="list" class="btn btn-secondary" onclick="addList()">Add List</button>
  </body>
  <script src="index.js" charset="utf-8"></script>

JAVASCRIPT

function addTask(){
  var input = document.createElement('input');
  input.placeholder="Enter task here";
  input.type="text";
  var br = document.createElement('br');
  var parent = document.getElementsByClassName('frm')[0];
  // parent.insertBefore(input,document.getElementsByClassName('lst')[0]);
  parent.appendChild(input);

}
function addList(){
  var div = document.createElement('div');
  div.innerHTML = document.getElementById('listTemp').innerHTML;
  div.className = 'ListBox';
  document.getElementsByTagName('body')[0].appendChild(div);
}

To refer div#project you can use document.querySelector('#project');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM