Reputation: 9
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
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