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');
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 tofalse
.
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.
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);