如何使用javascript的addChild方法向我的div添加节点?

时间:2011-05-26 17:43:14

标签: php javascript

你好我有一个div如下

<div id="test" class="test2">
<p> <a href=""> <a> </p>
<p> <a href=""> <a> </p>
<p> <a href=""> <a> </p>
<p> <a href=""> <a> </p>
</div>

(我删除了数据,但这是结构)

如何使用javascript的addChild函数添加新节点

<p> <a href=""> <a> </p>

我知道如何使用removeChild函数,但是我无法使用addChild函数找到文档和示例。

如果我在php数组中有节点字符串,并且可以通过按钮执行包含GET调用的数组的php脚本,请单击如何使用addChild函数将节点字符串放入div?

4 个答案:

答案 0 :(得分:3)

addChild是一个php函数,javascript函数名为appendChild

var dv = document.createElement("p");
dv.innerHTML = "<a href=""> </a> ";
document.getElementById('test').appendChild(dv)

另外,您可以将节点字符串附加到html: document.getElementById('test').innerHTML += '<p> <a href=""> <a> </p> '

答案 1 :(得分:1)

由于你拥有的是一个字符串,你首先需要为它创建一个DOM表示(你不能将字符串传递给appendChild,只能传递一个dom元素)。要做到这一点,最简单的方法是将其放在另一个元素中,然后获取其内容。

var temp = document.createElement('div'); // create a temporary dom element
temp.innerHTML = '<p><a href="#">some cool html string</a></p>'; // give it your html string as content, the browser will then create the corresponding dom representation
var childs = temp.childNodes; // grab the resulting child elements
document.getElementById('where_to_append').appendChild(childs); // append them to where you want

或者你可以通过使用innerHTML简单地设置它而不用appendChild:

var my_div = document.getElementById('where_to_append');
my_div.innerHTML = my_div.innerHTML + '<p><a href="#">some cool html string</a></p>';

答案 2 :(得分:0)

W3Schools使用adding a node

提供了appendChild()的示例

答案 3 :(得分:0)

您可以使用append()方法执行此操作。这是我定义new_child并添加到parent-div

的示例
var new_child = jQuery(document.createElement('p')).html("<p> <a href=""> <a></p>");

$('parent-div').append(new_child);