Acceso a los elementos HTML DOM 1 Acceso a elementos HTML Mediante JavaScriptes posible accesaren lectura y escritura los elementos de una página HTML. Es posible, por ejemplo: Cambiarla propiedadsrcde unaimagen Cambiarel contenidode 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 (DocumentObjectModel) 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ónyaqueno todoslos browsers la soportan. document.formname.inputname 6
<html><head><title>objects</title> Notación punto <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 <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> document.myform.mycheckbox 8
Notación punto 9 getelementbyid El métodogetelementbyid() regresaunareferenciaal 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() { varx=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ónde objetoscuyaetiquetacoincide 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étodoqueryselectorregresael primer elementoque 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étodoqueryselectorregresatodosloselementosque 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 otros elementos Hello <em> 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 P lastchild parentnode #text Sample nextsibling nodevalue property prevsibling firstchild, lastchild B #text bold nextsibling parentnode prevsibling #text display nodename property Stanford CS 142 Lecture Notes: DOM Slide 26
Métodos para modificar el DOM createelement() document createtextnode() createdocumentfragment() appendchild() node insertbefore() 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[] Algunas Propiedades innerhtml Id style Algunos Métodos blur() focus() 30
Text-box Por cada etiqueta <input type="text"> se crea un objeto texto. Algunas Propiedades value size Algunos Métodos select() focus() 31 Check-box Por cada etiqueta <input type= checkbox"> se crea un objeto checkbox Algunas Propiedades value checked Algunos Métodos click() 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