ParentNode.append()
El método ParentNode.append()
inserta un conjunto de objetos de tipo Node
u objetos de tipo DOMString
después del último hijo de ParentNode
. Los objetos DOMString
son insertados como nodos Text
(en-US) equivalentes.
Diferencias con Node.appendChild()
:
ParentNode.append()
te permite también agregar objetosDOMString
, mientras queNode.appendChild()
solo acepta objetosNode
.ParentNode.append()
no tiene valor de retorno, en cambio,Node.appendChild()
devuelve el objetoNode
agregado.ParentNode.append()
puede agregar varios nodos y cadenas, mientras queNode.appendChild()
sólo puede agregar uno.
Sintaxis
[Throws, Unscopable] void ParentNode.append((Node or DOMString)... nodes);
Parameters
Exceptions
HierarchyRequestError
: Node cannot be inserted at the specified point in the hierarchy.
Examples
Appending an element
var parent = document.createElement("div");
var p = document.createElement("p");
parent.append(p);
console.log(parent.childNodes); // NodeList [ <p> ]
Appending text
var parent = document.createElement("div");
parent.append("Some text");
console.log(parent.textContent); // "Some text"
Appending an element and text
var parent = document.createElement("div");
var p = document.createElement("p");
parent.append("Some text", p);
console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]
ParentNode.append()
is unscopable
The append()
method is not scoped into the with
statement. See Symbol.unscopables
(en-US) for more information.
var parent = document.createElement("div");
with(parent) {
append("foo");
}
// ReferenceError: append is not defined
Polyfill
You can polyfill the append() method
in Internet Explorer 9 and higher with the following code:
// Source: https://github.com/jserz/js_piece/blob/master/DOM/ParentNode/append()/append().md
(function (arr) {
arr.forEach(function (item) {
if (item.hasOwnProperty('append')) {
return;
}
Object.defineProperty(item, 'append', {
configurable: true,
enumerable: true,
writable: true,
value: function append() {
var argArr = Array.prototype.slice.call(arguments),
docFrag = document.createDocumentFragment();
argArr.forEach(function (argItem) {
var isNode = argItem instanceof Node;
docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem)));
});
this.appendChild(docFrag);
}
});
});
})([Element.prototype, Document.prototype, DocumentFragment.prototype]);
Specification
Specification | Status | Comment |
---|---|---|
DOM La definición de 'ParentNode.append()' en esta especificación. |
Living Standard | Initial definition. |
Browser compatibility
No compatibility data found for api.ParentNode.append
.
Check for problems with this page or contribute missing data to mdn/browser-compat-data.