Relembrando: Existem 4 tipos principais de nós: document, element, texto e atributo.
createElement
window.onload = function() {
/*Criação de Nós createElement*/
var div = document.getElementsByTagName("div").item(0);
var hr = document.createElement("hr");//cria uma linha
div.appendChild(hr);
}
Obs: Ao adicionar um nó dentro de outro ele será adicionado como filho desse elemento. Várias bibliotecas que usam Ajax para manipular dinamicamente as páginas, trazendo informações como o gmail, onde os emails aparecem sem recarregar a página. O efeito é conseguido dessa forma, usando a Dom Core Api.
No javaScript:
window.onload = function() {
var div = document.getElementsByTagName("div").item(0);
var li = document.createElement("li");
li.appendChild(document.createTextNode("Obrigado meu Deus"));//nó do tipo texto
div.lastChild.appendChild(li);
}
No javaScript:
window.onload = function() {
var div = document.getElementsByTagName("div").item(0);
var li = document.createElement("li");
li.appendChild(document.createTextNode("Obrigado meu Deus"));//nó do tipo texto
div.lastChild.appendChild(li);
var atributo = document.createAttribute("style");
atributo.value = "color:blue;
li.setAttributeNode(atributo); //core api
li.setAttribute("style", "color:orange"); //core api, forma simplificada
li.style.color = "purple"; //usando a dom html api
}
No javaScript:
window.onload = function() {
var div = document.getElementsByTagName("div").item(0);
var select = document.createElement("select");
select.setAttribute("id", "estados");
var option = document.createElement("option");
option.setAttribute("value", "MG");
option.appendChild(document.createTextNode("Minas Gerais"));
var option2 = document.createElement("option");
option2.setAttribute("value", "ES");
option2.appendChild(document.createTextNode("Espírito Santo"));
select.appendChild(option);
select.appendChild(option2);
div.appendChild(select);
}
No javaScript:
window.onload = function() {
var div = document.getElementsByTagName("div").item(0);
var del = div.lastChild; //remove o último elemento
div.removeChild(del);
}
var select2 = select.cloneNode(true); div.appendChild(select2); var option3 = option.cloneNode(true); select.appendChild(option3); } replaceChild