开发者

Why won't this script append a child div element?

开发者 https://www.devze.com 2023-03-03 11:08 出处:网络
When I click on the p element with an onclick attribute calling the make_child function I would expect it t开发者_如何学JAVAo append a div element when ever it is clicked but it seams to be only appen

When I click on the p element with an onclick attribute calling the make_child function I would expect it t开发者_如何学JAVAo append a div element when ever it is clicked but it seams to be only appending a text node to the paragraph element what is the cause of this?

<script type="text/javascript">
function make_child(text, id, type) {
    var text = document.createTextNode(text);
    var target = document.getElementById(id);
    var add = document.createElement(type);
    var addtext = add.appendChild(text);
    target.appendChild(addtext);
}
</script>

 <p id="changeme" onclick="make_child('I have changed', 'changeme', 'div')">Click me to change</p>


change the last line to this

target.appendChild(add);

now you are appending to the correct element


Try doing target.appendChild(add) instead of target.appendChild(addtext)

Edit (more detail): The syntax for appendChild (from MDN) is:

var child = element.appendChild(child);

Where child is the element being appended. In this case, addtext = add.appendChild(text) is set to text rather than add. Just doing target.appendChild(add) should solve this problem.

This also means the variable addtext is useless; you can remove it leaving only

add.appendChild(text)

for that line.

0

精彩评论

暂无评论...
验证码 换一张
取 消