Michael Lee Michael Lee - 1 month ago 8
HTML Question

Only plain text was shown when creating an HTML DOM element with appendChild() and createElement()

I made some code using the javascript

createElement()
and
appendChild()
, but it does not work. However, when I apply jQuery approach, it works normally. Can any one tell me why?



<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
function foo1(){
var test_btn = document.createElement("button").appendChild(document.createTextNode("test_btn"));
document.getElementById("WhyThisNothing").appendChild(test_btn);
}
function foo2(){
$('#WhyThisNothing').append('<button>test_btn</button>');
}
function foo3(){
$('#WhyThisNothing').append($('<button></button>',{text:"test_btn"}));
}
</script>
</head>
<body>
<button onclick="foo1()" id="btn">Click me then error 1:(</button>
<button onclick="foo2()" id="btn">Click me then ok 2:(</button>
<button onclick="foo3()" id="btn">Click me then ok 3:(</button>
<div id="WhyThisNothing"></div>
</body>
</html>




Answer

appendChild returns the appended child, not the parent it was appended to.

So, you have to append the text to the element separately, not chain it, as all you're left with is the textnode

function foo1(){
  var test_btn = document.createElement("button");

  test_btn.appendChild(document.createTextNode("test_btn"));

  document.getElementById("WhyThisNothing").appendChild(test_btn);
}