appendChild method
Inserts an element after the last child of the current element.
If the element has a parent element, then it will be removed from the parent element before the insertion.
The inserted element will be the last element in the childNodes collection of the current element.
- If you want to create a new element for insertion, use the createElement method first, then use the appendChild method for the newly created element.
- To insert an element before a specified child of the current element, use the insertBefore method.
- If you need to insert a new row into a table or a new cell into a row, you can also use the insertRow and insertCell methods.
- Or, if you want to remove a child from an element, use the removeChild method.
Syntax:
You can find the related objects in the Supported by objects section below.
Parameters:
Required. Reference to the element to insert. |
Return value:
Returns the newly inserted element.
Example HTML code 1:
This example illustrates the use of the appendChild method.
|
||||
<head> <script type="text/javascript"> function AddAChild () { var newElem = document.createElement ("div"); newElem.innerHTML = "sample text"; newElem.style.color = "red"; var container = document.getElementById ("container"); container.appendChild (newElem); } </script> </head> <body> <button onclick='AddAChild ();'>Add a div element to the container!</button> <div id="container"></div> </body> |
||||
|
||||
Did you find this example helpful?
|
Example HTML code 2:
This example uses the innerHTML property to implement the same functionality as the previous example:
|
||||
<head> <script type="text/javascript"> function AddAChild () { var container = document.getElementById ("container"); container.innerHTML += "<div style='color:red'>sample text</div>"; } </script> </head> <body> <button onclick='AddAChild ();'>Add a div element to the container!</button> <div id="container"></div> </body> |
||||
|
||||
Did you find this example helpful?
|
Supported by objects:
attribute, document, DocumentFragment, XMLDocument
HTML elements:
a, abbr, acronym, address, b, bdo, big, blink, blockquote, body, button, caption, center, cite, code, col, colgroup, dd, del, dfn, dir, div, dl, dt, em, fieldset, font, form, frameset, h1, h2, h3, h4, h5, h6, head, html, i, img, ins, kbd, keygen, label, legend, li, listing, map, marquee, menu, nobr, noframes, noscript, object, ol, optgroup, option, p, plaintext, pre, q, rt, ruby, s, samp, select, small, span, strike, strong, sub, sup, table, tbody, td, textarea, tfoot, th, thead, tr, tt, u, ul, var, xml, xmp
Related pages:
External links:
User Contributed Comments