luiyezheng luiyezheng - 6 months ago 12
Javascript Question

How to add an element to another one(instead of using selector)

I found in Document that I can create an element and add another one to it like:

var sel = document.createElement("select");
var opt1 = document.createElement("option");
var opt2 = document.createElement("option");

opt1.value = "1";
opt1.text = "Option: Value 1";

opt2.value = "2";
opt2.text = "Option: Value 2";

sel.add(opt1, null);
sel.add(opt2, null);


But when I tried to apply it to practice, this method doesn't work,
newUser
was not added to
newDiv
successfully:

function createOnEle(imgSrc, user, extract) {
var newDiv = document.createElement("div");
var newUser = document.createElement("span");

newUser.textContent = user;

newDiv.add(newUser);

}


It seems that
add
method doesn't work for
div
and
span
, if this is true, how to achieve it? Otherwise, Where did I wrong?

Answer

.add is a method of select-element which is used to add an option-element to it.

Refer HTMLSelectElement.add()

Use .appendChild()

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.

function createOnEle(user) {
  var newDiv = document.createElement("div");
  var newUser = document.createElement("span");
  newUser.textContent = user;
  newDiv.appendChild(newUser);
  document.body.appendChild(newDiv);
}
createOnEle('RogB :)')