Acceso a elementos HTML desde JavaScript

Anuncio
Acceso a los elementos XHTML
Acceso a los elementos XHTML
DOM
1
Acceso a elementos HTML
Acceso a elementos HTML
Mediante JavaScript es posible accesar en lectura y escritura los elementos de una página HTML.
i
l
l
d
á i HTML
Es posible, por ejemplo:
p
,p
j p
• Cambiar la la propiedad src de una imagen
• Cambiar el contenido
el contenido de un textbox
de un textbox
• Cambiar el color del background de un documento
• Leer el contenido de los campos de una forma
p
2
Acceso a elementos HTML
Acceso a elementos HTML
Para poder leer ó cambiar alguna propiedad de un objeto es necesario localizarlo
un objeto es necesario localizarlo.
En javaScript hay varias maneras de localizar objetos HTML:
• Mediante las colecciones del DOM
Mediante las colecciones del DOM
• Mediante la notación punto • Mediante el método document.getElementById()
Mediante el método document getElementById()
• Mediante el método document.getElementsByName()
• Mediante el método documente.getElementsByTagName()
• Navegando el árbol de nodos
3
Colecciones del DOM
Colecciones del DOM
DOM (Document Object Model) incluye 4 colecciones que agrupan objetos relacionados:
document.images
document
images
document.links
document.forms
document.anchors
4
Colecciones del DOM
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++)
{
d
document.write( document.links[i] + "<br
i (d
li k [i] " b />" );
/ ")
}
</script>
</form>
</body></html>
5
Notación punto
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
con precaución
no todos los browsers la los browsers la
soportan.
document.formname.inputname
6
Notación punto
Notación punto
<html><head><title>Objects</title>
<script language="JavaScript">
<!‐‐
function first() {
alert("la
alert(
la caja de texto contiene el string: 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+
myString+= "no
no esta marcado
esta marcado";;
alert(myString);
}
// ‐‐>
</script></head>
7
Notación punto
Notación punto
d
document.myForm.myCheckbox
t F
Ch kb
<body>
<form name="myForm">
<input type="text" name="myText" value="texto de prueba">
<input type="button" name="button1" value="Boton 1"
onClick first()
onClick="first()">
<br>
<input type="checkbox" name="myCheckbox" checked=“checked”>
<input type="button" name="button2" value="Boton 2"
onClick="second()">
Cli k "
d()"
</form>
</body>
y
</html>
8
Notación punto
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>
i l ID S
l /il
</head>
<body>
<p id=“simple”>He’s
<p id=
simple >He s pining for the fjords!</p>
pining for the fjords!</p>
<script language="javascript" type="text/javascript">
var parra1;
parra1 = document.getElementById(“simple”);
alert(parra1.innerHTML);
</script>
p
</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); }
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
value=
How many elements named many elements named 'myInput'?"
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)
g
y g
( g
)
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>
/body /html
15
JavaScript – CSS Equivalentes
JavaScript CSS Equivalentes
CSS
JavaScript
font--size
font
fontSize
font--weight
font
fontWeight
font-family
fontfont--style
font
fontFamily
fontStyle
text-decoration
textcolor
textDecoration
color
background-color
backgroundbackground--image
background
backgroundColor
backgroundImage
16
JavaScript – CSS Equivalentes
JavaScript CSS Equivalentes
var myH1Array = document.getElementsByTagName("H1"); var myElem = myH1Array.item(0); myH1Array item(0);
var myStyle = myElem.style; var fFamily = myStyle.fontFamily; var fSize = myStyle.fontSize; alert("H1 :\nfamily: " + fFamily + "\nsize: " + fSize);
Despliega el font y el tamaño del texto de los encabezados <h1>
17
Navegando el árbol de nodos
Navegando el árbol de nodos
Un documento HTML se representa como un árbol con elementos atributos y texto y define
árbol con elementos, atributos y texto y define así una manera de manipular los documentos
18
Un árbol DOM
Un árbol DOM
19
Ejemplo DOM
Ejemplo DOM
20
Ejemplo DOM
Ejemplo DOM
<p align="right">Hello <em>World</em></p>
<body>
otros
elementos
<p>
Hello
align
<em>
otros
elementos
right
World
21
Acceso a los nodos de un documento
Acceso a los nodos de un documento
TTodos los nodos del DOM son accesibles. Esto se d l
d d l DOM
ibl E t
logra de varias maneras:
• Usando los métodos ‐ getElementById(), getElementsByName() y getElementById() getElementsByName() y
getElementsByTagName() • Usando las propiedades ‐ parentNode, childNodes[], firstChild, and lastChild, nextSibling, previousSibling
22
Propiedades de los Nodos
Propiedades de los Nodos
nodeName
id
tagName
nodeValue
nodeType
attributes[]
getAttribute(), setAttribute(), removeAttribute()
23
Métodos para modificar el DOM
Métodos para modificar el DOM
createElement()
document
createTextNode()
createDocumentFragment()
appendChild()
insertBefore()
d
node
removeChild()
replaceChild()
p
24
Acceso a los nodos de un documento
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">
i
"
/j
i "
txt=document.getElementById("intro").childNodes[0].nodeValue;
document.write("The text from the intro paragraph: " + txt);
</script>
/ p
</body></html>
25
Descargar