colonialempire4
colonialempire4

Reputation: 9

Trouble in displaying an input element after the click of a button

I have a function that is supposed to add an input element to an existing div. I have tried using appendChild and have tried concatenating the object to the innerHTML but none of these have worked. Is there something here that my newbie's brain is forgetting?

function addSong() {
  const additionDiv = document.getElementById('track-controls');
  const trackFileInput = document.createElement('input');
  additionDiv.innerHTML += trackFileInput;
  const trackFile = trackFileInput.value;
  console.log('file saved'+trackFile);
}

Kindly assume that the outer variables and IDs are all present in other parts of the code. This function is referenced in the onclick property of a button. I have thoroughly checked for typos.

Upvotes: 0

Views: 33

Answers (1)

Daniel Beck
Daniel Beck

Reputation: 21514

You've mixed two competing methods for editing the DOM. innerHTML wants a string, but you're feeding it a DOM node instead (and then trying to concatenate that node with the existing html string). For a DOM node, you want to append the element (or use other DOM manipulation methods):

function addSong() {
  const additionDiv = document.getElementById('track-controls');

  const trackFileInput = document.createElement('input');
  additionDiv.appendChild(trackFileInput)
  
  const trackFile = trackFileInput.value; // note this will always be an empty string
  console.log('file saved' + trackFile);
}

addSong()
<div id="track-controls"></div>

Upvotes: 1

Related Questions