18.04.2016 Views

Professional JavaScript For Web Developers

javascript for learners.

javascript for learners.

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 6<br />

<br />

<br />

DOM Example<br />

<br />

<br />

<br />

<br />

What color do you like?<br />

Red<br />

Green<br />

Blue<br />

<br />

<br />

<br />

<br />

<br />

This page asks the user which color he/she likes. The radio buttons all have the same name, because you<br />

only want to return one value for this field, which is the value attribute of the selected radio button. To<br />

get references to all the radio button elements, you can use the following code:<br />

var oRadios = document.getElementsByName(“radColor”);<br />

You can then manipulate the radio buttons the same way as you can any other element:<br />

alert(oRadios[0].getAttribute(“value”)); //outputs “red”<br />

Internet Explorer 6.0 and Opera 7.5 have a couple of bugs when using this method.<br />

First, they also return elements that have an id equal to the given name. Second,<br />

they only check and elements.<br />

getElementById()<br />

The second method defined by the HTML DOM is getElementById(), which returns an element with<br />

its id attribute set to a specific value. In HTML, the id attribute is unique — meaning that no two elements<br />

can share the same id. This is undoubtedly the fastest method of retrieving a single specific element<br />

from the document tree.<br />

Suppose you have the following HTML page:<br />

<br />

<br />

DOM Example<br />

<br />

<br />

Hello World!<br />

This is my first layer<br />

<br />

<br />

172

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!