您的位置:首页 > Web前端 > JavaScript

Javascript DOM 编程艺术:dom 节点及操作节点方法

2012-08-23 22:25 399 查看
element nodes

text nodes

attribute nodes
There are quite a few other types of nodes. Comments are a separate node type, for
instance. But I’d just like to mention one more node type here.
Attributes are used to give more specific information about an element. The title attribute,
for example, can be used on just about any element to specify exactly what the element
contains:
<p title="a gentle reminder">Don’t forget to buy this stuff.</p>
In the Document Object Model, title="a gentle reminder" is an attribute node, as shown in Figure 3-2. Because attributes are always placed within opening tags, attribute nodes are always contained within element nodes.
Not all elements contain attributes, but all attributes are contained by elements.



The Node object represents a node in the HTML document.

A node in an HTML document is:

The Document

An element

An attribute

Text

A comment

getElementById

var element = document.getElementById('foo');

返回值:The element with the matching
ID
; or
null
if no matching element is found.

如果typeof element;会输出object.In fact, every single element in a document is an object.

null always evaluates to false

If the element doesn't exist then this method will return
null
. Therefore a condition that depends on the existence of an element can be written like this:

if(document.getElementById('foo')) { ... }

Because the ECMAScript specification requires that
null
evaluates to
false
.

getElementsByTagName

element.getElementsByTagName(tag)

Get an ordered list of all elements with a given tag name, that are descendents of this document or element, in the linear order in which they appear in the DOM tree.以线性排列。

The returned collection is a
NodeList
— an ordered collection of nodes, indexed numerically starting from zero. If there are no matching elements then it's a collection with zero members.

记住:没有元素,也是collection,只是大小为0.

A collection is not an array
Even though a collection looks like an array, it isn't an array — although you can iterate through it and refer to its members like an array, you can't use
Array
methods like
push
or
pop
on it.

Here’s a quick summary of what you’ve seen so far:
A document is a tree of nodes.
There are different types of nodes: elements, attributes, text, and so on.
You can get straight to a specific element node using getElementById.
You can get straight to a collection of element nodes using getElementsByTagName.
Every one of these nodes is an object.

getAttribute

object.getAttribute(attribute)

Unlike the other methods you’ve seen, you can’t use getAttribute on the document object. It can only be used on an element node object.

/ 获取属性 attr 的值
object.getAttribute(attr);
// 为属性 attr 设置值
object.setAttribute(attr, value);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: