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

The Document Object Model

42 404 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

Tiêu đề The Document Object Model
Trường học University Name
Chuyên ngành Computer Science
Thể loại Essay
Định dạng
Số trang 42
Dung lượng 426,29 KB

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

Nội dung

The tree representation of an HTML document primarily contains nodes representing elements or tags such as and and nodes representing strings of text.. 17.1.2.1 Types of nodes Differe

Trang 1

Chapter 17 The Document Object

Model

document object model (DOM) is an application programm g interface (API) for

ocument JavaScript-enabled web browsers have always defi ed a document object

In this chapter, we'll discuss the W3C DOM, a standard document object model defined

by the World Wide Web Consortium and implemented (at least partially) by Netscape 6

[1] Technically, the W3C issues "recommendations." These recommendations serve the same purpose and carry the same weight as international standards do, however, and are called "standards" in this book

This chapter begins with an overview of the DOM standard and then describes the core portions of the standard for working with HTML documents The discussion of the core standard is followed by short sections that explain the DOM-like features of Internet

s of nced

HTML documents have a hierarchical structure that is represented in the DOM as a tree structure The nodes of the tree represent the various types of content in a document The tree representation of an HTML document primarily contains nodes representing

elements or tags such as <body> and <p> and nodes representing strings of text An

Explorer 4 and Netscape 4 The chapter ends with an overview of two optional part

the DOM standard that are closely related to the core Later chapters cover adva

DOM features for working with style sheets and events

17.1 An Overview of the DOM

The DOM API is not particularly complicated, but before we can begin our discussion of programming with the DOM, there are a number of things you should understand about the DOM architecture

17.1.1 Representing Documents as Trees

Consider the following simple HTML document:

Trang 2

The DOM can also be used to represent XML documents, which have a more complex syntax than HTML documents, and the tree representation of such a document may contain nodes that represent XML entity references, processing instructions, CDATA sections, and so

on Most client-side JavaScript programmers do not need to use the DOM with XML documents, and although the XML-specific features of the DOM are covered in the DOM reference section, they are not emphasized in this chapter.

Figure 17-1 The tree representation of an HTML document

If you are not already familiar with tree structures in computer programming, it is helpfu

to know that they borrow terminology from family trees The node directly above a node

is the

l

e

17.1.2 Nodes

parent of that node The nodes one level directly below another node are the

children of that node Nodes at the same level, and with the same parent, are siblings Th

set of nodes any number of levels below another node are the descendants of that node And the parent, grandparent, and all other nodes above a node are the ancestors of that

node

of Node objects The Node interface

s

[3] defines properties and methods for traversing and

Trang 3

previousSibling, and parentNode properties provide a way to traverse the tree o

nodes Methods such as

f

The DOM standard defines interfaces, not classes If you are not familiar with the term interface in object-oriented programming, you can

think of it as an abstract kind of class We'll describe the difference in more detail later in this DOM overview

17.1.2.1 Types of nodes

Different types of nodes in the document tree are represented by specific subinterfaces of

example, you know the Node object is also an Element object and you can use all the

appendChild( ) , removeChild( ),replaceChild( ), and

insertBefore( ) enable you to add and remove nodes from the document tree We'll see examples of the use of these properties and methods later in this chapter

[3]

lists the node

Table 17-1 Common node types

property of this object refers to an Element object that represents the root element of the document For HTML documents, this is the <html> tag that is either explicit or implicit

which represent tags such as <html> and <i>, and Text objects, which represent strings

the DOM tree by Comment

ment (The Document node may have other children, such as Commen

to the root element.) The bulk of a DOM tree consists of Element obje

objects Figure 17-2 shows a partial class hierarchy for these

Trang 4

Figure 17-2 A partial class hierarchy of the core DOM API

, setAttribute(

property that allows you to determine whether the attribute is literally specified in the

17-2, and it is a type of node Note, however, that Attr objects do not appear in the

childNodes[] array of an element and are not directly part of the document tree in theway that Element and Text nodes are The DOM specification allows Attr nodes to be

impossible to use this feature portably

17.1.3 The DOM HTML API

The DOM standard was designed for use with both XML and HTML documents The core DOM API the Node, Element, Document, and other interfaces are relatively generic and apply to both types of documents The DOM standard also includes

HTMLDocument is an HTML-specific subinterface of Document, and HTMLElement is

an HTML-specific subinterface of Element Furthermore, the DOM defines tag-specific interfaces for many HTML elements These tag-specific interfaces, such as

Trang 5

HTMLBodyElement and HTMLTitleElement, typically define a set of properties that mirror the HTML tag's attributes

The HTMLDocument interface defines various document properties and methods that

Chapter 14, and Chapter 15

properties These properties allow convenient access to the values of the id,style,

title,lang,dir, and class attributes, which are allowed on all HTML tags A number

of HTML tags, listed in Table 17-2, accept no attributes other than these six, and so are fully represented by the HTMLElement interface

Table 17-2 Simple HTML tags

<abbr> <acronym> <address> <b> <bdo>

<big> <center> <cite> <code> <dd>

<dfn> <dt> <em> <i> <kbd>

<noframes> <noscript> <s> <samp> <small>

<span> <strike> <strong> <sub> <sup>

andsetAttribute( ) methods of the Element object

a set of properties that mirror their HTML attributes For example, the <ul> tag has a

HTMLBodyElement interface Because these interfaces simply define properties that astandardized by the HTML standard, they are not documented in detail in this book You can safely assume that the HTMLElement object that represents a particular HTML tag has properties for each of the standard attributes for that tag (but see the naming

conventions described in the next section) Note that the DOM standard defines

properties for HTML attributes as a "convenience" to script writers The general (and possibly pref

Trang 6

Some of the interfaces defined in the HTML DOM define additional properties or

methods, other than those that mirror HTML attribute values For example, the

ave been made part of the DOM standard for backward compatibility with existing practice Interfaces like these are documented in the DOM reference section You can usually also find information about the "existing practice" portions of these interfaces in the client-side reference section, although this information is typically referenced under a name that also predates DOM standardization; for example, you can find information about HTMLFormElement and HTMLInputElement in the client-side reference section

When w

ple words, the first

re capitalized Thus, the maxlength attribute

nput> tag translates into the maxLength property of HTMLInputElement

When an HTML attribute name conflicts with a JavaScript keyword, it is prefixed with the string "html" to avoid the conflict Thus, the for attribute of the <label> tag

is the class attribute (which can be specified for any HTML element); it translates to the

className property of HTMLElement.[4]

property Methods and properties like these typically predate DOM standardization and h

under "Form" and "Input."

17.1.3.1 HTML naming conventions

orking with the HTML-specific portions of the DOM standard, you should be

L-specific interfaces aware of some simple naming conventions Properties of the HTM

e property name consists of multibegin with lowercase letters If th

letters of the second and subsequent words a

of the <i

[4]

The name className is misleading, because in addition to specifying a single class name, this property (and the HTML attribute it represents) can also specify a space-separated list of class names

17.1.4 DOM Levels and Features

There are two versions, or "levels," of the DOM standard DOM Level 1 was

standardized in October, 1998 It defines the core DOM interfaces, such as Node,

Element, Attr, and Document, and also defines various HTML-specific interfaces DOM

interfaces, this new version of the DOM is greatly expanded to define standard APIs for working with document events and CSS style sheets and to provide additional tools for

er

Level 1 standard

working with ranges of documents As of this writing, the DOM Working Group at the W3C is working to standardize DOM Level 3 You may also sometimes see a reference

to DOM Level 0 This term does not refer to any formal standard but is used to ref

informally to the common features of the HTML document object models implemented

by Netscape and Internet Explorer prior to W3C standardization

[5]

Except for the HTML-specific portions of the standard, which are still at the "working draft" stage as of November 2001 Fortunately, the current working draft is presumed stable and includes only minor changes (documented in this book) from the HTML-specific portions of the

Trang 7

As of Level 2, the DOM standard has been "modularized." The core module, which

nt, and

s are o

implementation The DOM implementation of a web browser would obviously support

defines the basic tree structure of a document with the Document, Node, Eleme

Text interfaces (among others), is the only required module All other module

ptional and may or may not be supported, depending on the needs of the

the HTML module, since web documents are written in HTML Browsers that support CSS style sheets typically support the StyleSheets and CSS modules, because (as we'll

Similarly, since almost all interesting client-side JavaScript programming requires

event-o suppevent-ort the Events mevent-odule event-of

ot yet widely supported at the time of this writing e'll see a complete list of DOM Level 2 modules in the next section

s most

handling capabilities, you would expect web browsers t

Events moduthe DOM Level 2 specification and is n

W

17.1.5 DOM Conformance

At the time of this writing, no browser is completely conformant to the DOM standard Recent releases of Mozilla come closest, and complete DOM Level 2 conformance is a goal of the Mozilla project Netscape 6.1 does a good job of conforming to the most important Level 2 modules, and Netscape 6.0 does an adequate job but has gaps in its coverage Internet Explorer 6 is mostly compliant (with at least one annoying exception) with the Level 1 DOM, but does not support many of the Level 2 module

have substantial gaps in their conformance but support key DOM Level 1 methods well enough to run most of the examples in this chapter The Macintosh version of IE 5 has considerably better support for the DOM than the Windows version of IE 5

In addition to Mozilla, Netscape, and Internet Explorer, several other browsers offer at least partial support for the DOM The number of available browsers has become too large, and the rate of change in the area of standards support has grown too fast, for this book to even attempt to provide definitive statements about which browsers support which particular DOM features Therefore, you'll have to rely on other information sources to determine exactly how conformant the DOM implementation in any particuweb browser is

One source for conformance information is the implementation itself In a con

lar

formant cument object refers to a

ing

es

this method (if it exists) to ask an implementation whether it supports a specific feature (or module) of the DOM standard For example, to determine whether the DOM

implementation in a web browser supports the basic DOM Level 1 interfaces for workwith HTML documents, you could use the following code:

Trang 8

ThehasFeature( ) method takes two arguments: the first is the name of the feature to check, and the second is a version number, expressed as a string It returns true if the specified version of the specified feature is supported Table 17-3 lists the feature name/version number pairs that are defined by the DOM Level 1 and Level 2 standards Note that the feature names are case-insensitive: you can capitalize them any way you support of a feature and are therefore implied by a return value of true For example, if

indicates that the MouseEvents module is supported, this implies that

Table 17-3 Features that can be tested with hasFeature

Views)

Events,Views

Trang 9

In Internet Explorer 6 (on Windows), hasFeature( ) returns true only for the feature HTML and Version 1.0 It does not report compliance to any of the other features listed

inTable 17-3 (although, as we'll see in Chapter 18, it supports the most common uses of

e names

and version numbers, with the notable exceptions of the Traversal and MutationEvents features It returns false for the Core and CSS2 features with Version 2.0, indicating

good)

incomplete support (even though support for these features is quite

includes complete coverage of all modules

section

6ith

too voluminous and volatile to include in a printed book

an active web developer, you undoubtedly already know or will discover many

t

e of this writing, the test suite effort is just

ThehasFeature( ) method is not always perfectly reliable As previously noted, IE reports Level 1 compliance to HTML features even though there are some problems wits compliance On the other hand, Netscape 6.1 reports noncompliance to the Level 2

ture even though it is mostly compliant In both cases, you need more detailed Core fea

information about exactly what is and is not compliant This is exactly the type of

The Mozilla organization has a set of test suites for a variety of standards, including

has published a test suite that includes some DOM Level 2 tests (available

athttp://developer.netscape.com/evangelism/tools/testsuites/ ) Netscape has also

published a partisan (and dated) comparison of DOM compliance of an early Mozilla release versus IE 5.5 (available at

http://home.netscape.com/browsers/future/standards.html) Finally, you can also find compatibility and compliance information at independent sites on the Web One notable site is published by Peter-Paul Koch You can find a link to his DOM Compatibility

17.1.5.1 DOM conformance in Internet Explorer

Because IE is the most widely used web browser, a few special notes about its

5 and later versions support the Level 1 Core and HTML features well enough to run the examples in this compliance to the DOM specifications are appropriate here IE

Trang 10

chapter, and they support the key Level 2 CSS features well enough to run most of the

Events module, even though Microsoft participated in the definition of this module and

crucial for client-side event handling, and IE's lack of support for the standard event

ismodel impedes the development of advanced client-side web applications

gious problem, and the one you are most likely to encounter, is a minor but

de interface

fat

e = { // If there is no Node object, define one

llowing properties and

e are HTML node types EXT_NODE: 3, // For XML-specific nodes, you need to add COMMENT_NODE: 8, // other constants here

DOCUMENT_NODE: 9,

}

17.1.6 Language-Independent DOM Interfaces

Although the DOM standard grew out of a desire to have a common API for dynamic

to be language-independent This book describes only the JavaScript binding of the DOM

eHTML interfaces of the DOM Level 1 standard, this support is actually incomplete Thmost egre

annoying one: IE does not support the node-type constants defined by the No

node it is The DOM specification also says that the Node interface defines constants th

represents an Element node In IE (at least as high as version 6), these constants simply

The examples in this chapter have been modified to work around this problem by using integer literals instead of the corresponding symbolic constants For example, you'll see code like this:

if (n.nodeType == 1 /*Node.ELEMENT_NODE*/) // Check if n is an Eleme

HTML programming, the DOM is not of interest only to web scripters In fact, the

standard is currently most heavily used by server-side Java and C++ programs that parseand manipulate XML documents Because of its many uses, the DOM standard is defined

Trang 11

API, but you should be aware of a few other points First, note that object properties inthe JavaScript binding are typically mapped to pairs of get/set methods in other language

JavaScript binding of the Node

firstChild property, and reading the value of this property in JavaScript is equal to

Another important feature of the JavaScript binding of the DOM API is that certain DOM

objects that implement that interface behave like read-only numerical arrays For

of a node You can obtain the individual Node objects in the list by passing the desired

object as an array and index it directly The following code illustrates these two options:

var n = document.documentElement; // This is a Node object

var children = n.childNodes; // This is a NodeList object

var head = children.item(0); // Here is one way to use a

NodeList.

var body = children[1]; // But this way is easier!

is the same as using the string as an array index for the object For example, the following lines of code are all equivalent ways to access a form element:

var f = document.forms.namedItem("myform");

var g = document.forms["myform"];

var h = document.forms.myform;

Because the DOM standard may be used in a variety of ways, the architects of the

standard were careful to define the DOM API in a way that would not restrict the ability

of others to implement the API as they saw fit Specifically, the DOM standard defines interfaces instead of classes In object-oriented programming, a class is a fixed data type that must be implemented exactly as specified An interface, on the other hand, is a collection of methods and properties that must be implemented together Thus, an

implementation of the DOM is free to define whatever classes it sees fit, but those classes must define the methods and properties of the various DOM interfaces

This architecture has a couple of important implications First, the class names used in an implementation might not correspond directly to the interface names used in the DOM standard (and in this book) Second, a single class may implement more than one

interface For example, consider the Document object This object is an instance of some class defined by the web browser implementation We don't know what the specific class

is, but we do know that it implements the Document interface; that is, all methods and properties defined by Document are available to us through the Document object Since

of the Node interface, you need to understand that the

Trang 12

web browsers work with HTML documents, we also know that the Document object implements the HTMLDocument interface and that all methods and properties defined by that interface are available to us as well Furthermore, if a web browser supports CSS style sheets and implements the DOM CSS module, the Document object also

implements the DocumentStyle and DocumentCSS DOM interfaces And if the web browser supports the Events and Views modules, Document implements the

DocumentEvent and DocumentView interfaces as well

Because the DOM is broken into independent modules, it defines a number of minor

add-on interfaces, such as DocumentStyle, DocumentEvent, and DocumentView, that define only one or two methods each Interfaces such as these are never implemented

independently of the core Document interface, and for this reason, I do not documentthem independently When you look up the Document interface in the DOM reference section, you'll find that it also lists the methods and properties of its various add-on interfaces Similarly, if you look up one of the add-on interfaces, you'll simply find a cross-reference to the core interface with which it is associated The exception to this rule

is when the add-on interface is a complex one For example, the HTMLDocument

interface is always implemented by the same object that implements the Document

object, but because it adds substantial new functionality, I have given it a reference page

of its own

Another important fact you need to understand is that since the DOM standard defines interfaces instead of classes, it does not define any constructor methods If you want to create a new Text object to insert into a document, for example, you cannot simply say:

var t = new Text("this is a new text node"); // No such constructor!

Since it cannot define constructors, the DOM standard instead defines a number of useful

factory methods for creating objects in the Document interface So, to create a new Text

node for a document, you would write the following:

var t = document.createTextNode("this is a new text node");

Factory methods defined by the DOM have names that begin with the word "create" In addition to the factory methods defined by Document, a few others are defined by

17.2 Using the Core DOM API

Now that we've studied the tree structure of documents and seen how the tree is

composed of Node objects, we can move on to study the Node object and document trees

in more detail As I noted previously, the core DOM API is not terribly complex The following sections contain examples that demonstrate how you can use it to accomplishcommon tasks

Trang 13

17.2.1 Traversing a Document

As we've already discussed, the DOM represents an HTML document as a tree of Node objects With any tree structure, one of the most common things to do is traverse the tree,

JavaScript function that recursively examines a node and all its children, adding up the number of HTML tags (i.e., Element nodes) it encounters in the course of the traversal

NodeList object, which behaves (in JavaScript) like an array of Node objects Thus, the function can enumerate all the children of a given node by looping through the elements

a given node, but all nodes in the tree of nodes Note that this function also demonstrates

Example 17-1 Traversing the nodes of a document

ment object, it traverses the entire DOM tree

untTags(n) { // n is a Node

tags = 0; // Initialize the tag counter

var children = n.childNodes; // Now get all children

ength; i++) { // Loop through the children

numtags += countTags(children[i]); // Recurse on each one

Trang 14

Another point to notice about Example 17-1 is that the countTags( ) function it defines

is invoked from the onload event handler, so that it is not called until the document is completely loaded This is a general requirement when working with the DOM: you cannot traverse or manipulate the document tree until the document has been fully

loaded

op

properties.firstChild and lastChild refer to the first and last children of a node, and

nextSibling and previousSibling refer to adjacent siblings of a node (Two nodes are siblings if they have the same parent node.) These properties provide another way to lo

number of characters in all the Text nodes within the <body> of the document Notice the

if that

of the node and adds up the total length

de he t

odeType == 3 /*Node.TEXT_NODE*/) // Check if n is a Text return n.length; // If so, return its

length

// Otherwise, n may have children whose characters we need to count var numchars = 0; // Used to hold total characters of the children // Instead of using the childNodes property, this loop examines the // children of n using the firstChild and nextSibling properties for(var m = n.firstChild; m != null; m = m.nextSibling) {

numchars += countCharacters(m); // Add up total characters found

properties to loop through the children of a node

Example 17-2 Another way to traverse a document

// itself on each of the children

// of the text it finds Note that it enumerates the children of a no // using the firstChild and nextSibling properties Note also that t // function does not recurse when it finds a Text node, because Tex nodes

// never have children

function countCharacters(n) { // n is a Node

Trang 15

17.2.2 Fin

The ability to traverse all nodes in a document tree gives us the power to find

nodes When programming with the DOM API, it is quite

node within the document or a list of nodes of a specific type within the document

InExample 17-2, we referred to the <body> element of an HTML document with the

convenient special-case property and is the preferred way to refer to the <body> tag of an

document If this convenience property did not exist, however, we could also

returns an array of all <body> elements within the document Since HTML do

can have only one <body>, we know that we're interested

[6]

returned array

[6]

Technically, the DOM API specifies that getElementsByTagName( ) returns a NodeList object In the JavaScript bindin

of the DOM, NodeList objects behave like arrays and are typically used that way

g

getElementsByTagName( )

For example, to find all the tables within a document, you'd do this:

var tables = document.getElementsByTagName("table");

alert("This document contains " + tables.length + " tables");

Note that since HTML tags are not case-sensitive, the strings passed to

getElementsByTagName( ) are also not case-sensitive That is, the previous code finds

<table> tags even if they are coded as <TABLE>.getElementsByTagName( ) returns elements in the order in which they appear in the document Finally, if you pass the special string "*" to getElementsByTagName( ), it returns a list of all the elements in the document, in the order in which they appear (This special usage is not supported in

reference section.)

Trang 16

Sometimes you don't want a list of elements but instead want to operate on a single specific element of a document If you know a lot about the structure of the document,

something to the fourth paragraph in a document, you might use this code:

var myParagraph = document.getElementsByTagName("p")[3];

o

the

e for the element Then you can look up

graph = document.getElementById("specialParagraph");

rn an array of elements like every id attribute is (or is

uite programming

getElementById( ) and getElementsByTagName( ) are both methods of the

t specific makes it possible, for example, to

getElementsByTagName( ) does Because the value of

n DOM

common i

getElementsByTagName( )

however This method of the Element object behaves just like the method of the

Document object, except that it returns only elements that are descendants of the elemen

on which it is invoked Instead of searching the entire document for elements of a

type, it searches only within the given element This

getElementById( )

getElementsByTagName( ) to find all descendants of a given type within that specitag For example:

var rows = tableOfContents.getElementsByTagName("tr");

var numrows = rows.length;

Trang 17

Finally, note that for HTML documents, the HTMLDocument object also defines a

etElementsByName( ) method This method is like getElementById( ), but it looks

at the name attribute of elements rather than the id attribute Also, because the name

attribute is not expected to be unique within a document (for example, radio buttons

ents

t the real power of the core DOM API lies in the features that allow you to

documents and illustrate some of the possibilities

Example 17-3

g

array of elements rather than a single element For example:

// Find <a name="top">

var link = document.getElementsByName("top")[0];

// Find all <input type="radio" name="shippingMethod"> elem

var choices = document.getElementsByName("shippingMethod");

17.2.3 Modifying a Document

Traversing the nodes of a document can be useful, bu

use JavaScript to dynamically modify llowing examples demonstrate the basic techniques o

node that represents the <body> element of the document (Note the use of

getElementsByTagName( ) within the button's event handler to find the <body>

reverse the order of those children

Example 17-3 Reversing the nodes of a document

<head><title>Reverse</title>

<script>

function reverse(n) { // Reverse the order of the children of Node n

var kids = n.childNodes; // Get the list of children

var numkids = kids.length; // Figure out how many children there are

for(var i = numkids-1; i >= 0; i ) { // Loop backward through the children

var c = n.removeChild(kids[i]); // Remove a child

n.appendChild(c); // Put it back at its new position

Trang 18

>Click Me to Reverse</button>

</body>

The result of Example 17-3, illustrated in Figure 17-3, is that when the user clicks the button, the order of the paragraphs and of the button are reversed

Figure 17-3 A document before and after being reversed

we couldeep in mind

modified, the modifications are immediately visible through the NodeList This is an

ually make some code trickier

ings

e of the

that is already part of the document to appendChild( ) it first removes it, so

) Second, k

property (like all NodeList objects) is "live": when the documthat the chi

important features of the NodeList interface, but it can act

that follow that child, so if you want to iterate through a NodeList and delete som

nodes, you must write your looping code carefully

Example 17-4 shows a variation on the reverse( ) function of the previous example

all

This one uses recursion to reverse not only the children of a specified node, but alsothe node's descendants In addition, when it encounters a Text node, it reverses the order

shows only the JavaScript code for thisnewreverse( ) function It could easily be used in an HTML document like the one

Example 17-4 A recursive node-reversal function

rsively reverse all nodes beneath Node n and reverse Text nodes

Trang 19

else { // For non-Text nodes, recursively reverse the order of th children

e

; gth;

for(var i = numkids-1; i >= 0; i ) { // Loop through kids

kid to new position

}

}

xample 17-4

var kids = n.childNodes

var numkids = kids.len

reverse(kids[i]); // Recurse to

reverse kid

n.appendChild(n.removeChild(kids[i])); // Move

}

defines a function, uppercase( ), that recursively traverses the children of a given node When it finds a Text node, the function replaces that node with a new Text node

containing the text of the original node, converted to uppercase Note the use of the

document.createTextNode( ) method to create the new Text node and the use of

property to determine the parent of the Text node it replaces

Each paragraph is identified with a unique name, specified with

ercase(n) {

if (n.nodeType == 3 /*Node.TEXT_NODE*/) {

// If the node is a Text node, create a new Text node that // holds the uppercase version of the node's text, and use the // replaceChild( ) method of the parent node to replace the // original node with the new uppercase node

e( )); parent.replaceChild(newNode, n);

n

paragraphs and a button When the user clicks the button, one of the paragraphs is

converted to uppercase

theid attribute of the <p> tag The event handler on the button uses the

getElementById( ) method to get the Element object that represents the desired

paragraph

Example 17-5 Replacing nodes with their uppercase equivalents

<script>

// This function recursively looks at Node n and its descendants,

// replacing all Text nodes with their uppercase equivalents

nction upp

fu

var newNode = document.createTextNode(n.data.toUpperCas

var parent = n.parentNode;

Trang 20

for(var i = 0; i < kids.length; i++) uppercase(kids[i]);

"CharacterData" in the DOM reference section

attributes >

<p id="p1">This <i>is</i> paragraph 1.</p>

<p id="p2">This <i>is</i> paragraph 2.</p>

<! Here is a button that invokes the uppercase( ) function defin above >

<! Note the call to document.getElementById( ) to find the desired node >

<button onclick="uppercase(document.getElementById('p1'));">Click

Me</button>

The previous two examples show how to modify document content by replacing the textcontained within a Text node and by replacing one Text node with an entirely new Text node It is also possible to append, insert, delete, or replace text within a Text node with theappendData( ) , insertData( ),deleteData( ), and re

aracterData You can find more information about them under

appendChild( ) methods to reorder the children of a Node Note, however, that we are not restricted to changing the order of nodes within their parent node; the DOM API allows nodes in the document tree to be moved freely within the tree (only within the

embolden( ) that replaces a specified node with a new element (created with the

createElement( ) method of the Document object) that represents an HTML <b> tag and "reparents" the origi al node as a child of the new node In an HTML document, this causes any text within the node o

r its descendants to be displayed in boldface

s the original node // child of the new <b> element

the

the <b> tag

bold.appendChild(node); // Make the node a c

of the <b> tag

Trang 21

</script>

onclick="embolden(document.getElementById('p1'));">Embolden</button>

ply e

eleme Attribute( ) method For example:

ed adline.setAttribute("align", "center"); // Set

define JavaScript properties that

as align),

he previous two examples showed how the contents of a Text node can be changed to

> node

dd them ary

ent This is

<! A couple of sample paragraphs >

<p id="p1">This <i>is</i> paragraph #1.</p>

<p id="p2">This <i>is</i> paragraph #2.</p>

<! A button that invokes the embolden( ) function on the first

The DOM elements that represent HTML attributes

correspond to each of their standard attributes (even deprecated attributes such

so you can also achieve the same effect with this code:

var headline = document.getElementById("headline");

headline.align = "center"; // Set alignment attribute.

17.2.4 Adding Content to a Document

T

uppercase and how a node can be reparented to be a child of a newly created <b

new nodes and aTheembolden( ) function showed that it is possible to create

content to a document by creating the necess

to a document You can add arbitrary

em appropriately to the docum

document.createTextNode( ) and by adding th

nd it

of

function provides a convenient way to insert debugging messages into a program, aserves as a useful alternative to using the built-in alert( ) function A sample usethisdebug( ) function is illustrated in Figure 17-4

Figure 17-4 Output of the debug( ) function

Ngày đăng: 05/10/2013, 13:20

TỪ KHÓA LIÊN QUAN