Acceso a los elementos HTML DOM 1 Acceso a elementos HTML Mediante JavaScript es posible accesar en lectura y escritura los elementos de una página HTML. Es posible, por ejemplo: • Cambiar la propiedad src de una imagen • Cambiar el contenido de un textbox • Cambiar el color del background de un documento • Leer el contenido de los campos de una forma 2 Acceso a elementos HTML Para poder leer ó cambiar alguna propiedad de un objeto es necesario localizarlo. En javaScript hay varias maneras de localizar objetos HTML: • Mediante las colecciones del DOM • Mediante la notación punto • Mediante el método document.getElementById() • Mediante el método document.getElementsByName() • Mediante el método document.getElementsByTagName() • Mediante el método document.querySelector() • Mediante el método document.querySelectorAll() • Navegando el árbol de nodos 3 Colecciones del DOM DOM (Document Object Model) incluye 4 colecciones que agrupan objetos relacionados: document.images document.links document.forms document.anchors 4 Colecciones del DOM <html><head> <title>JavaScript Document Object Example</title> </head> <body> <a href="http://www.amazon.com">Buy more books</a> <br /> <a href="http://www.yahoo.com">Stop making Google rich</a> <br /> <script language="javascript" type="text/javascript"> for (var i=0; i<document.links.length; i++) { document.write( document.links[i] + "<br />" ); } </script> </form> </body></html> 5 Notación punto Algunos browsers permiten accesar las formas y sus elementos como una propiedad del documento utilizando el atributo name. Esta facilidad debe usarse con precaución ya que no todos los browsers la soportan. document.formname.inputname 6 Notación punto <html><head><title>Objects</title> <script language="JavaScript"> <!-function first() { alert("la caja de texto contiene el string: " + document.myForm.myText.value); } function second() { var myString= "El checkbox "; if (document.myForm.myCheckbox.checked) myString+= "esta marcado" else myString+= "no esta marcado"; alert(myString); } // --> </script></head> 7 Notación punto document.myForm.myCheckbox <body> <form name="myForm"> <input type="text" name="myText" value="texto de prueba"> <input type="button" name="button1" value="Boton 1" onClick="first()"> <br> <input type="checkbox" name="myCheckbox" checked= "checked"> <input type="button" name="button2" value="Boton 2" onClick="second()"> </form> </body> </html> 8 Notación punto 9 getElementById El método getElementById() regresa una referencia al primer objeto cuyo id coincida con el especificado. document.getElementById(id) 10 getElementById <html><head> <title>ID Sample</title> </head> <body> <p id=“simple”>He’s pining for the fjords!</p> <script language="javascript" type="text/javascript"> var parra1; parra1 = document.getElementById(“simple”); alert(parra1.innerHTML); </script> </body> </body></html> 11 getElementsByName El método getElementsByName () regresa una colección de objetos con el nombre especificado. document.getElementsByName(name) 12 getElementsByName <html> <head> <script type="text/javascript"> function getElements() { var x=document.getElementsByName("myInput"); alert(x.length); } </script> </head> <body> <input name="myInput" type="text" size="20" /><br /> <input name="myInput" type="text" size="20" /><br /> <input name="myInput" type="text" size="20" /><br /> <br /> <input type="button" onclick="getElements()" value="How many elements named 'myInput'?" /> </body> </html> 13 getElementsByTagName El método getElementsByTagName () regresa una colección de objetos cuya etiqueta coincide con el nombre especificado. document.getElementsByTagName(tagname) 14 getElementsByTagName <html><head> <script type="text/javascript"> function getElements(){ var x=document.getElementsByTagName("input"); alert(x.length);} </script> </head><body> <input name="name" type="text" size="20" /><br /> <input name="address" type="text" size="20" /><br /> <input name="school" type="text" size="20" /><br /> <br /> <input type="button" onclick="getElements()" value="How many input elements?" /> </body></html> 15 document.querySelector El método querySelector regresa el primer elemento que coincide con un selector CSS específico en el documento. document.querySelector(CSS Selectors) Si se especifican varios selectores separados por comas el método regresa el primer element que cumple con alguno de los selectors. 16 document.querySelector <!DOCTYPE html> <html> <body> <h2 class="example">A heading with class="example"</h2> <p class="example">A paragraph with class="example".</p> <p>Click the button to add a background color to the first element in the document with class="example".</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { document.querySelector(".example").style.backgroundColor = "red"; } </script></body></html> 17 document.querySelectorAll El método querySelector regresa todos los elementos que coinciden con un selector CSS específico en el documento. document.querySelectorAll(CSS Selectors) Si se especifican varios selectores separados por comas el método regresa el primer element que cumple con alguno de los selectors. 18 document.querySelectorAll <!DOCTYPE html> <html> <body> <h2 class="example">A heading with class="example"</h2> <p class="example">A paragraph with class="example".</p> <p>Click the button to add a background color to the first element in the document with class="example".</p> <button onclick="myFunction()">Try it</button> <script> function myFunction() { document.querySelectorAll(".example")[0].style.backgroundColor = "red"; document.querySelectorAll(".example")[1].style.backgroundColor = "green"; } </script></body></html> 19 Navegando el árbol de nodos Un documento HTML se representa como un árbol con elementos, atributos y texto y define así una manera de manipular los documentos 20 Un árbol DOM 21 Ejemplo DOM 22 Ejemplo DOM <p align="right">Hello <em>World</em></p> <body> otros elementos <p> align Hello <em> otros elementos right World 23 Acceso a los nodos de un documento Todos los nodos del DOM son accesibles. Esto se logra de varias maneras: • Usando los métodos - getElementById(), getElementsByName() y getElementsByTagName() • Usando las propiedades - parentNode, childNodes[], firstChild, and lastChild, nextSibling, previousSibling 24 Propiedades de los Nodos nodeName id tagName nodeValue nodeType attributes[] getAttribute(), setAttribute(), removeAttribute() 25 <p>Sample <b>bold</b> display</p> firstChild lastChild P parentNode nextSibling nextSibling B #text Sample #text prevSibling prevSibling firstChild, lastChild display parentNode nodeName property #text nodeValue property bold Stanford CS 142 Lecture Notes: DOM Slide 26 Métodos para modificar el DOM createElement() document createTextNode() createDocumentFragment() appendChild() insertBefore() node removeChild() replaceChild() 27 Acceso a los nodos de un documento <html><body> <p id="intro">Hello World!</p> <p id="main">This is an example for the HTML DOM tutorial.</p> <script type="text/javascript"> txt=document.getElementById("intro").childNodes[0].nodeValue; document.write("The text from the intro paragraph: " + txt); </script> </body></html> 28 Acceso a las propiedades de los elementos HTML mediante JavaScript 29 HTMLElement attributes[] innerHTML Algunas Propiedades Id style blur() Algunos Métodos focus() 30 Text-box Por cada etiqueta <input type="text"> se crea un objeto texto. value Algunas Propiedades size select() Algunos Métodos focus() 31 Check-box Por cada etiqueta <input type=“checkbox"> se crea un objeto checkbox value Algunas Propiedades checked click() Algunos Métodos 32 Acceso al estilo de presentación de los elementos HTML Los objetos correspondientes a los elementos HTML contienen un objeto denominado STYLE que representa las reglas de estilo aplicadas sobre el elemento. EJEMPLO … myH1=document.getElementById("myH1"); H1Style=myH1.style; H1Style.color="red"; 33 JavaScript – CSS Equivalentes CSS JavaScript font-size fontSize font-weight fontWeight font-family fontFamily font-style fontStyle text-decoration textDecoration color color background-color backgroundColor background-image backgroundImage 34 EJEMPLO <html> <head> <script> function pintar(){ myH1=document.getElementById("myH1"); H1Style=myH1.style; H1Style.color="red"; } </script> </head> <body onload=“pintar()"> <h1>UNO</h1> <h1 id="myH1">DOS</h1> </body> </html> UNO DOS 35