Método appendChild() do XML DOM
Definição e Uso
appendChild()
O método adiciona um novo nó filho ao final da lista de filhos do nó.
Atenção:Se newchild Se o nó já estiver na árvore, primeiro o exclua.
Sintaxe
nodeObject.appendChild(newchild)
Parâmetros | Descrição |
---|---|
newchild | Nó a ser adicionado. |
Detalhes Técnicos
Versão DOM: | Objeto Node de Nível de Núcleo 1. Modificado no DOM Level 3. |
---|---|
Retorno: | Objeto Node. Nó anexado. |
Exemplo
Exemplo 1
O código a seguir carrega "books.xml" para xmlDoc, cria um nó (<edition>) e o anexa após o último filho do primeiro nó <book>:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { minhaFuncao(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function minhaFuncao(xml) { var xmlDoc = xml.responseXML; var newel = xmlDoc.createElement("edition"); var x = xmlDoc.getElementsByTagName("book")[0]; x.appendChild(newel); document.getElementById("demo").innerHTML = x.getElementsByTagName("edição")[0].nodeName; }
Exemplo 2
Adicionar os filhos a todos os nós <livro>:
var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { minhaFuncao(this); } }; xhttp.open("GET", "books.xml", true); xhttp.send(); function minhaFuncao(xml) { var x, y, z, i, xLen, yLen, newEle, newText, xmlDoc, txt; xmlDoc = xml.responseXML; txt = ""; x = xmlDoc.getElementsByTagName("livro"); xLen = x.length; for (i = 0; i < xLen; i++) { newEle = xmlDoc.createElement("edição"); newText = xmlDoc.createTextNode("primeiro"); newEle.appendChild(newText); x[i].appendChild(newEle); } // Imprimir todos os títulos e edições y = xmlDoc.getElementsByTagName("título"); yLen = y.length z = xmlDoc.getElementsByTagName("edição"); for (i = 0; i < yLen; i++) { txt += y[i].childNodes[0].nodeValue + " - Edição: " + z[i].childNodes[0].nodeValue + "<br>"; } document.getElementById("demo").innerHTML = txt; }
Suporte do Navegador
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
Suporte | Suporte | Suporte | Suporte | Suporte |
Todos os navegadores principais suportam o método appendChild().