22.06.2015 Views

o_19octlt3v29m1ul81r9513q81i4ra.pdf

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

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

JavaScript, Briefly 291<br />

The example shown in the preceding exercise placed the tags and the JavaScript<br />

code within the tag. You can also place tags and related code within<br />

the block.<br />

JavaScript includes methods for choosing or selecting elements on a page. For example,<br />

the JavaScript method getElementById() selects an element on a Web page based on its<br />

id attribute. JavaScript includes other similar methods as well, such as getElementsbyTag<br />

Name() which returns all the elements of a certain tag type, such as all the elements<br />

on a page.<br />

In the following exercise, you will retrieve the element that has an id attribute of<br />

contentDiv (as you saw in the previous exercise) and change its background color to<br />

a shade of gray.<br />

SET UP Use the Javascript01.html file that you created in the previous exercise. Open<br />

the file in Notepad, if it is not already open.<br />

1. Delete the following line from the code:<br />

alert("hello world");<br />

2. Between the and tags, place the following:<br />

<br />

var divContent = document.getElementById("contentDiv");<br />

divContent.style.backgroundColor = "#abacab";<br />

<br />

3. Save your work in Notepad.<br />

4. Open the file in Internet Explorer to test it. Instead of a Hello World dialog box, the<br />

text on the page appears with a gray background:<br />

CLEAN UP Close Internet Explorer. Leave the Javascript01.html file open in Notepad<br />

for the next exercise.<br />

In this example, the code retrieves the element identified in the page with the id of<br />

contentDiv by using the getElementById method. It places that element into a variable<br />

called divContent and uses that variable with another JavaScript function, style(), to<br />

change the div element’s backgroundColor property value to #abacab.

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

Saved successfully!

Ooh no, something went wrong!