javascript - Can someone explain to me: appending elements to a target vs. assigning elements to a target? -
i made 2 simple functions can see in link . when first button clicked, create h3 element, create text, append text in element, , append element in id called results. but, when click on second button pretty same thing, except asked innerhtml of results , assign h3 element. but, when "[object htmlheadingelement] ". wondering why response though feel they're both doing same thing
html:
<button id="click"> click </button> <button id="click2"> click 2 </button> <div id="results"> hello </div>
javascript:
document.getelementbyid('click').onclick = function() { var = document.createelement('h3'); var b = document.createtextnode('this text!'); a.appendchild(b); document.getelementbyid('results').appendchild(a); } document.getelementbyid('click2').onclick = function() { var = document.createtextnode('this other text'); var b = document.createelement('h3'); var c = ""; b.appendchild(a); c +=b document.getelementbyid('results').innerhtml = c; }
when try convert object
string
value, toprimitive()
method called internally , return string representation of object
. here in our case string representation of node object "[object htmlheadingelement]"
. being assigned innerhtml of #results
element.
finally, if want extract raw html string of element have access outerhtml
property. solution in case outerhtml
of created element , assign target's innerhtml
.
document.getelementbyid('results').innerhtml = b.outerhtml;
and full code be,
document.getelementbyid('click2').onclick = function() { var = document.createtextnode('this other text'); var b = document.createelement('h3'); b.appendchild(a); document.getelementbyid('results').innerhtml = c.outerhtml; }
Comments
Post a Comment