1. Trang chủ
  2. » Công Nghệ Thông Tin

Học JavaScript qua ví dụ part 70 ppsx

12 183 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 12
Dung lượng 1,14 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

15.4 Walking with the DOM In Example 15.1, we will take a walk down the DOM tree, one step at a time, using the parent/child/sibling nodes to represent each element in the document.. 10

Trang 1

15.4 Walking with the DOM

In Example 15.1, we will take a walk down the DOM tree, one step at a time, using the

parent/child/sibling nodes to represent each element in the document The simple

lay-out of the HTML page is drawn in Figure 15.6 You can quickly see that using DOM

properties to navigate the tree can get confusing, and if in any way the structure of the

document changes, then all the nodes properties will have to be reset We discuss a

quicker more efficient way to get around in the next section

Because every element in the tree has a parent (other than the root node), a

relation-ship can be established going up or down the tree as long as you know which node and

which children will lead you to the target element you want The five properties for each

node in the tree are parentNode, firstChild, lastChild, previousSibling, and next Sibling.

Figure 15.6 The DOM tree for Example 15.1.

E X A M P L E 1 5 1

1 <html>

<head><title>The Nodes</title>

<style>

p{font-size: x-large; color:darkblue;

font-style:bold;

}

</style>

</head>

<body>

<h1>Walking with Nodes</h1>

<p>Who knows what node?</p>

<p>

document

<html> root node

<head>

“The Nodes”

<body>

“Walking with the Nodes”

Trang 2

<script type="text/javascript">

2 var Parent=document.childNodes[0];

// First child node is HTML

3 var Child=Parent.childNodes[0];

// Parent’s first child is HEAD

document.write("The parent node is: ");

4 document.write(Parent.nodeName+"<br />");

// Get the name parent node

document.write("The first child of the parent node is: ");

5 document.write(Child.nodeName+"<br />");

document.write("The node below the child is: ");

6 document.write(Child.childNodes[0].nodeName+"<br />");

document.write("The text node below title is: ");

7 document.write(Child.childNodes[0].childNodes[0].nodeName +

"<br />");

document.write("The value of the text node is: " +

8 Child.childNodes[0].childNodes[0].nodeValue+"<br />");

document.write("The first child of the parent is: ");

9 document.write(Parent.firstChild.nodeName+"<br />");

document.write("The last child of the parent is: ");

10 document.write(Parent.lastChild.nodeName+"<br />");

document.write("The node below the body is: ");

11 document.write(Parent.lastChild.childNodes[0].nodeName+

"<br />");

document.write("The next sibling of the h1 element is: ");

12

document.write(Parent.lastChild.childNodes[0].nextSibling.nodeName+

"<br />");

document.write("It's value is " +

"Parent.lastChild.childNodes[0].nextSibling.nodeValue);

13 document.write("<br />The last child's type is: ");

document.write(Parent.lastChild.nodeType);

</script>

</p>

</body>

</html>

E X P L A N A T I O N

1 The JavaScript program will access the HTML elements through the DOM

where each element is viewed as a node This line cannot be broken for

format-ting due to the whitespace bug If you break up this line, the whitespace created

will be considered a text node, and the rest of the script will not display the

nodes as expected

Continues

E X A M P L E 1 5 1 (C O N T I N U E D)

Trang 3

2 The first node, childNodes[0], is the first node in the HTML hierarchy, the parent

node This node is assigned to a variable, Parent The only reason to create the

variable is to cut down on the amount of typing and propensity for errors when

we go further down the document tree Note: Watch your spelling when working

with the DOM in JavaScript

3 The parent node’s first child is document.childNodes[0].childNodes[0] This

por-tion of the tree is assigned to the variable Child.

4 The name of a node is found in the nodeName property The parent node is HTML,

the highest element in the HTML hierarchy

5 The nodeName of the first child of the parent node is HEAD.

6 The next node in the hierarchy is the child of the HEAD element It is the title

element:

<html>

<head>

<title>

7 Continuing the walk down the DOM tree, we come to the text node It contains

the text between the <title> </title> tags The name of the text node is preceded by

a # mark

8 The actual text between the <title></title> tags is found in the nodeValue property

of the node

9 Using the firstChild property to simplify things, the first child of the parent again

shows to be the HEAD element.

10 The last child of the HTML parent is the BODY element:

<html>

<head>

<body>

11 The node directly below the body is the h1 element:

<body><h1>Walking with the Nodes</h2>

12 The node below the body (i.e., the last child of the body element),

document.child-Nodes[0].lastChild.nodeName, is the h1 element.

13 The parent’s last child node’s type is 1 An element node type is type 1, an attribute

type is type 2, and a text node is type 3 See Figure 15.7

E X P L A N A T I O N (C O N T I N U E D)

Trang 4

15.5 DOM Inspectors

A DOM inspector is a browser tool that lets you dynamically traverse the DOM tree and

check CSS styles, in a two-paned window as shown in Figure 15.8 Now you can view

the markup in your Web page and all the nodes and their types for those parts of the

page that are of interest to you

For Firefox: see https://developer.mozilla.org/en/dom_inspector.

For Internet Explorer see: http://www.ieinspector.com/dominspector/

For Opera go to the menu: Tools→Advanced→Developer Tools

Figure 15.7 The node properties.

Trang 5

15.6 Methods to Shorten the DOM Walk

In the previous example, walking with the nodes was like walking through a maze in a

palace garden Although the DOM is represented as a hierarchal tree of elements, where

each element is represented as a node, walking with the nodes can be daunting, so the

W3C provides additional methods and properties to help make the walk easier

The DOM provides two methods, getElementById() and getElementsByTag(), to

directly access the target element you are trying to reach It also provides properties to

represent attributes of an element listed in Table 15.5

Using the id attribute is not a new idea We have been using it throughout this text All

browsers that comply with the W3C’s DOM1+ should implement the id attribute for

accessing the elements in a document It uniquely identifies any HTML element in a

Web document Note: This is not the same as the name attribute discussed in Chapters

11 and 12 If you recall, the name attribute is used with forms, images, links, and

anchors The name attribute does not have to be unique and is used by the browser to

create name/value pairs to be submitted to a server program as part of the URL (GET

method) or HTTP header (POST)

The HTML element’s id attribute must be assigned a unique value that is used as a

CSS selector to identify a style rule or to get a reference to that element in a JavaScript

Figure 15.8 The Firefox DOM Inspector.

Trang 6

program In Chapter 11 when working with forms, we used both the name and id

attri-butes When working with DOM nodes, the id attribute allows you to specify a specific

node and retrieve a reference to it with the document.getElementByID() method, a DOM1

method

Although all major browsers are DOM1 compliant, here is a little test code you can

run to check your browser:

if (document.getElementById){

alert("DOM compliant!");

}

Go to http://www.webreference.com/tools/browser/JavaScript.html to see examples of

“browser sniffer” programs—programs that can tell what browser is being used

All that node stuff can be really tricky, but by combining the HTML id attribute with

the getElementById() method of the document object, it is much easier to get a handle on

any HTML object The getElementById() method takes the id of an HTML element as its

argument and returns a reference to that element (Remember that getElementById() is

a method of the document object and must be written as document.getElementById())

With the reference you can manipulate the element in your JavaScript code Suppose

you have a paragraph tag defined with an id attribute, as:

<p id="para1">This is the paragraph.</p>

Now in JavaScript you can get a reference to the p element with the getElementById()

method as follows:

p_element = document.getElementById("para1");

Rather than descending the entire DOM tree, p_element is a reference to the p element

identified as “para1” and can be used with the DOM properties:

alert(p_element.nodeName); // Name of the element alert(p_element.childNodes[0].nodeValue); // Text between tags

Example 15.2 demonstrates the use of the id attribute on several HTML elements

After getting a reference to the element, the DOM node properties can be applied to the

reference

E X A M P L E 1 5 2

<html>

<head><title>The Dom and Id's</title></head>

1 <body id="body1">

2 <h1 id="head1">Shortening the DOM Walk</h1>

3 <p id="para1">This is the paragraph!<p/>

<p><big>

Continues

Trang 7

<script name="text/javascript">

4 var h1tag=document.getElementById("head1");

5 var bodytag=document.getElementById("body1");

6 var paratag = document.getElementById("para1");

7 h1tag.style.fontFamily="verdana";

h1tag.style.fontSize="32";

h1tag.style.color="darkgreen";

paratag.style.fontSize="125%";

paratag.style.color="blue";

bodytag.style.backgroundColor="silver";

8 document.write(h1tag +"<br />");

document.write(paratag+"<br />");

document.write(bodytag+"<br /><br />");

//Let's get the text between the tags

document.write("<h2>This is the text within

the tags:</h2>");

9 document.write(h1tag.childNodes[0].nodeValue+"<br />");

document.write(paratag.childNodes[0].nodeValue+"<br />");

</script>

</big>

</p>

</body >

</html>

E X P L A N A T I O N

1 The <body> tag is given an id called “body1”.

2 The <h1> tag is given an id called “head1”.

3 The <p> tag is given an id called “para1”.

4 In the JavaScript program, the getElementById() method returns a reference to an

h1 element, and assigns that value to the variable called h1tag.

5 The getElementById() method returns a reference to a BODY element, and assigns

that value to the variable called bodytag.

6 The getElementById() method returns a reference to a p element, and assigns that

value to the variable called paratag.

7 Now, by using the style property, the elements are assigned new values for font size

and color, causing them to change dynamically

8 The value returned by the getElementById() method is displayed for each of the

elements As shown in the output, each one of these HTML elements is an object

See Figure 15.9

E X A M P L E 1 5 2 (C O N T I N U E D)

Trang 8

To reference a collection of elements in a document, such all the <p> tags, <h1> tags, or

<a> tags in your document, you can use the getElementsByTagName() method This

method takes the name of the element as its argument and returns a list of all the nodes

of that name in the document If you need to collectively change the values of a

partic-ular element, such as all the links in an <a> tag, do this by manipulating the reference

returned by the getElementsByTagName() Use the DOM nodes to continue walking

down the tree from the point of reference retrieved from

document.getElementsByTag-Name() method as shown in Example 15.3.

9 Rather than starting at the top of the DOM tree to obtain the text between the

HTML tags, it is easier to get a reference to the tag and then add the DOM

prop-erties to the reference as shown here An even easier way to fetch the text value

between the tags is to use the innerHTML property described later in this chapter.

Figure 15.9 HTML elements are objects.

E X P L A N A T I O N (C O N T I N U E D)

Trang 9

E X A M P L E 1 5 3

<html>

<head><title>Working with Tags</title>

<style type="text/css">

body {background-color:aliceblue;color:green;

font-size:larger;}

h1{color:darkblue; }

</style>

</head>

<body>

1 <h1> First</h1>

<h1> Second</h1>

<h1> Third</h1>

2 <script type="text/javascript">

3 var heading1=document.getElementsByTagName("h1");

document.write(heading1 + "<br />");

document.write("There are "+

4 heading1.length+ " H1 tags.<br />");

5 for(i=0; i< heading1.length; i++){

6 document.write( heading1[i].nodeName+": <em>"+

7 heading1[i].childNodes[0].nodeValue+"</em><br />");

}

</script>

</body>

</html>

E X P L A N A T I O N

1 Three <h1> tags are used in this document.

2 Because of the top-down processing by the HTML renderer, be sure to put the

JavaScript program at the end of the document This way, the tags will already

have been identified before they are put into the HTML collection returned by the

getElementsByName() method.

3 The HTML collection of h1 tags is stored as an array of nodes in the variable,

heading1.

4 The length of the array is 3 in this example because there are three H1 elements

in the document See Figure 15.10

5 The for loop will iterate through each of the heading1 tag objects in the HTML

col-lection

6 The nodeName property contains the name of the HTML element.

7 The child of the h1 element, childNodes[i], (where i is the index value) is the text

between the <h1> tags The nodeValue property contains the actual text.

Trang 10

15.6.3 JavaScript Properties to Represent HTML Attributes

The attributes of an HTML element are accessible as properties in JavaScript Table 15.5

lists the properties available to JavaScript to test an attribute

Figure 15.10 Getting elements by tag name:

Mozilla Firefox (left), Internet Explorer (right).

Table 15.5 Properties to Represent HTML Attributes

className Represents the class of a CSS element div2.className="blue";

div2 refers to an HTML element

It is being assigned the CSS class

called blue (see Example 15.17)

dir Specifies the text direction for a document;

for example, read left to right (English), or right to left (Hebrew); ltr (left to right) or rtl (right to left)

element.dir="ltr";

id Value of the unique id of the current element (see Section 15.6.1)

the document is written; for example, en for English, ja for Japanese, and sp for Spanish

if(document.lang=="ja")

Continues

Ngày đăng: 04/07/2014, 02:20

TỪ KHÓA LIÊN QUAN