LEARNING JAVASCRIPT - Trang 284

font

-

family

:

monospace

;

}

<

/style>

<

/head>

<

body

>

<

header

>

<

h1

>

Simple

HTML

<

/h1>

<

/header>

<

div

id

=

"content"

>

<

p

>

This

is

a

<

i

>

simple

<

/i> HTML file.</p>

<

div

class

=

"callout"

>

<

p

>

This

is

as

fancy

as

we

'

ll

get

!<

/p>

<

/div>

<

p

>

IDs

(

such

as

<

span

class

=

"code"

>

#

content

<

/span>)

are

unique

(

there

can

only

be

one

per

page

).

<

/p>

<

p

>

Classes

(

such

as

<

span

class

=

"code"

>

.

callout

<

/span>)

can

be

used

on

many

elements

.

<

/p>

<

div

id

=

"callout2"

class

=

"callout fancy"

>

<

p

>

A

single

HTML

element

can

have

multiple

classes

.

<

/p>

<

/div>

<

/div>

<

/body>

<

/html>

Every node has the properties

nodeType

and

nodeName

(among others).

nodeType

is

an integer identifying what type of node it is. The

Node

object contains constants that

map to these numbers. The types of node we’ll be primarily dealing with in this chap‐

ter are

Node.ELEMENT_NODE

(HTML elements) and

Node.TEXT_NODE

(text contents,

usually within HTML elements). For more information, see the

MDN documentation

for

nodeType

.

It’s an instructive exercise to write a function that traverses the entire DOM and prints

it to the console, starting with

document

:

function

printDOM

(

node

,

prefix

) {

console

.

log

(

prefix

+

node

.

nodeName

);

for

(

let

i

=

0

;

i

<

node

.

childNodes

.

length

;

i

++

) {

printDOM

(

node

.

childNodes

[

i

],

prefix

+

'\t'

);

}
}

printDOM

(

document

,

''

);

This recursive function does what’s known as a

depth-first, pre-order traversal of a

tree. That is, it follows branches all the way before moving on to the next branch. If

you run it in a browser with a page loaded, you will see the entire structure of the

page printed out to the console.
While this is an instructive exercise, it would be a tedious and inefficient way to

manipulate HTML (having to traverse the entire DOM to find what you’re looking

260 | Chapter 18: JavaScript in the Browser

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.