Document Object Model (DOM)








Todo el material usado en estas transparencias se han obtenido de:
Web Programming Step by Step, 2 ed., Jessica Miller, Victoria Kirst, Marty Stepp. Lulu. 2012



Valid HTML5 Valid CSS

Objetos de elementos DOM

El árbol DOM

DOM tree

Tipos de nodos DOM

<p>
	This is a paragraph of text with a 
	<a href="/path/page.html">link in it</a>.
</p>
DOM Tree

Propiedades de objeto DOM

<div id="main" class="foo bar">
	<p>Hello, <em>very</em> happy to see you!</p>
	<img id="icon" src="images/borat.jpg" alt="Borat" />
</div>
Property Description Example
tagName element's HTML tag document.getElementById("main").tagName is "div"
className CSS classes of element document.getElementById("main").className is "foo bar"
innerHTML content inside element document.getElementById("main").innerHTML is "\n <p>Hello, <em>ve...
src URL target of an image document.getElementById("icon").src is "images/borat.jpg"

Propiedades de controles de formulario DOM

<input id="sid" type="text" size="7" maxlength="7" />
<input id="frosh" type="checkbox" checked="checked" /> Freshman?
Property Description Example
value the text in an input control document.getElementById("sid").value could be "1234567"
checked whether a box is checked document.getElementById("frosh").checked is true
disabled whether a control is disabled (boolean) document.getElementById("frosh").disabled is false
readOnly whether a text box is read-only document.getElementById("sid").readOnly is false

Modificación del texto dentro de un elemento

let paragraph = document.getElementById("welcome");
paragraph.innerHTML = "Welcome to our site!";  // change text on page

los objetos de elementos DOM tiene las siguientes propiedades:

Abuso de innerHTML

// bad style!
let paragraph = document.getElementById("welcome");
paragraph.innerHTML = "<p>text and <a href="page.html">link</a>";

Cambio de estilos con DOM

<button id="clickme">Color Me</button>
window.onload = function() {
	document.getElementById("clickme").onclick = changeColor;
};
function changeColor() {
	let clickMe = document.getElementById("clickme");
	clickMe.style.color = "red";
}
Property Description
style lets you set any CSS style property for an element

Errores comunes de estilo DOM

Estilo discreto

function okayClick() {
	this.style.color = "red";
	this.className = "highlighted";
}
.highlighted { color: red; }

El árbol DOM

Recorrido del árbol DOM

cada objeto del árbol DOM tiene las siguientes propiedades:

name(s) description
firstChild, lastChild start/end of this node's list of children
childNodes array of all this node's children
nextSibling, previousSibling neighboring nodes with the same parent
parentNode the element that contains this node

Ejemplo de recorrido del árbol DOM

<p id="foo">This is a paragraph of text with a 
	<a href="/path/to/another/page.html">link</a>.</p>
navigate tree

Nodos elemento vs. texto

<div>
	<p>
		This is a paragraph of text with a 
		<a href="page.html">link</a>.
	</p>
</div>

Seleccionando grupos de objetos DOM

name description
getElementsByTagName(tag) returns array of descendents with the given tag, such as "div"
getElementsByName(name) returns array of descendents with the given name attribute (mostly useful for accessing form controls)
querySelector(selector) returns the first element that would be matched by the given CSS selector string
querySelectorAll(selector) returns an array of all elements that would be matched by the given CSS selector string

Obtención de todos los elementos de un tipo

resaltar todos los párrafos del documento:

let allParas = document.querySelectorAll("p");
for (let i = 0; i < allParas.length; i++) {
	allParas[i].style.backgroundColor = "yellow";
}
<body>
	<p>This is the first paragraph</p>
	<p>This is the second paragraph</p>
	<p>You get the idea...</p>
</body>

Selectores complejos

resaltar todos los párrafos dentro de la sección con ID "address":

// let addrParas = document.getElementById("address").getElementsByTagName("p");
let addrParas = document.querySelectorAll("#address p");
for (let i = 0; i < addrParas.length; i++) {
	addrParas[i].style.backgroundColor = "yellow";
}
<p>This won't be returned!</p>
<div id="address">
	<p>1234 Street</p>
	<p>Atlanta, GA</p>
</div>

Creación de nuevos nodos

name description
document.createElement("tag") creates and returns a new empty DOM node representing an element of that type
document.createTextNode("text") creates and returns a text node containing given text
// create a new <h2> node
let newHeading = document.createElement("h2");
newHeading.innerHTML = "This is a heading";
newHeading.style.color = "green";

Modificando el árbol DOM

Cada objeto elemento DOM tiene estos métodos:

name description
appendChild(node) places given node at end of this node's child list
insertBefore(newold) places the given new node in this node's child list just before old child
removeChild(node) removes given node from this node's child list
replaceChild(newold) replaces given child with new node
let p = document.createElement("p");
p.innerHTML = "Un resultado!";
document.getElementById("main").appendChild(p);

Eliminación de un nodo de la página

function slideClick() {
	let bullets = document.getElementsByTagName("li");
	for (let i = 0; i < bullets.length; i++) {
		if (bullets[i].innerHTML.indexOf("children") >= 0) {
			bullets[i].parentNode.remove(bullets[i]);
		}
	}
}

Piratería DOM versus innerHTML

Porqué no codificar el ejemplo anterior de la siguiente forma?

function slideClick() {
	document.getElementById("thisslide").innerHTML += "<p>A paragraph!</p>";
}
  • Imaginar que el nuevo nodo es más complejo:
    • feo: mal estilo en varios niveles (p.e. código JS incrustado dentro de HTML)
    • propenso a errores: debe distinguir cuidadosamente " y '
    • se puede agregar al inicio o final, no en medio de la lista de hijos
function slideClick() {
	this.innerHTML += "<p style='color: red; " +
			"margin-left: 50px;' " +
			"onclick='myOnClick();'>" +
			"A paragraph!</p>";
}