I'm trying to create an element, and then append another element to the element before passing it to the document. I'm not sure why my code won't work, been testing out different methods.
var count = 0;
function addElement() {
count++;
// Create plan element
var newElement = document.createElement("li");
newElement.classList.add("collection-item");
var main = document.createElement("div");
var side = document.createElement("a");
side.classList.add("secondary-content");
main.appendChild(side);
newElement.appendChild(main);
// append element to plan layout
planDesign.appendChild(newElement);
// get values
var exercise = newExcersise.value;
var set = newSet.value;
var rep = newRep.value;
main.innerHTML = "<span>" + count + ".</span>" + exercise;
side.innerHTML = "<span>Sets: </span>" + set + " <span>Reps: </span>" + rep;
}
I'm trying to create an element, and then append another element to the element before passing it to the document. I'm not sure why my code won't work, been testing out different methods.
var count = 0;
function addElement() {
count++;
// Create plan element
var newElement = document.createElement("li");
newElement.classList.add("collection-item");
var main = document.createElement("div");
var side = document.createElement("a");
side.classList.add("secondary-content");
main.appendChild(side);
newElement.appendChild(main);
// append element to plan layout
planDesign.appendChild(newElement);
// get values
var exercise = newExcersise.value;
var set = newSet.value;
var rep = newRep.value;
main.innerHTML = "<span>" + count + ".</span>" + exercise;
side.innerHTML = "<span>Sets: </span>" + set + " <span>Reps: </span>" + rep;
}
I need to get the created "a" element to be inserted into the "div".
Share Improve this question asked Dec 11, 2017 at 0:36 Sander HellesøSander Hellesø 2711 gold badge7 silver badges16 bronze badges 1-
1
main.innerHTML =
this replaces the innerHTML ofmain
... including theside
element – Jaromanda X Commented Dec 11, 2017 at 0:39
1 Answer
Reset to default 5You are using two different techniques to acplish the same thing and it's causing you to overwrite your main
element's content when you say:
main.innerHTML = "<span>" + count + ".</span>" + exercise;
after successfully appending the side
element into main
.
Be consistent when you can. You are using document.createElement()
, element.innerHTML
and element.appendChild()
- different ways of doing the same thing.
If you change the code so that you use the DOM API for creating new nodes (as opposed to creating HTML out of concatenated strings), you will be able to better control the configuration of your elements and where they go.
var spn = document.createElement("span");
spn.textContent = count + ".";
main.appendChild(spn);
var text = document.createTextNode(exercise);
main.appendChild(text);