How to use the addChild method of javascript to add a node to my div?
Hello I have a div as follows
<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>
(I have stripped out the data but that is the structure)
How does one use 开发者_StackOverflow社区the addChild function of javascript to add a new node
<p> <a href=""> <a> </p>
I know how to use the removeChild function but I haven't been able to find documentation and examples using the addChild function.
If I have the node string in a php array, and can execute the php script containing the array with a GET call via a button click how can I use the addChild function to put the node string into the div?
addChild
is a php function, The javascript function is called appendChild
:
var dv = document.createElement("p");
dv.innerHTML = "<a href=""> </a> ";
document.getElementById('test').appendChild(dv)
Alternativly, you can append the node string to the html:
document.getElementById('test').innerHTML += '<p> <a href=""> <a> </p>
'
Since what you have is a string, you first need to create a DOM representation of it (you can't pass a string to appendChild, only a dom element). To do that the easiest way is to put it inside another element and then take its content.
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
Or you could simply set it without appendChild by using innerHTML anyway:
var my_div = document.getElementById('where_to_append');
my_div.innerHTML = my_div.innerHTML + '<p><a href="#">some cool html string</a></p>';
You can use the append()
method to do that. Here is an example where I defined the new_child
and added to the parent-div
var new_child = jQuery(document.createElement('p')).html("<p> <a href=""> <a></p>");
$('parent-div').append(new_child);
W3Schools has examples for adding a node using appendChild()
精彩评论