Node - Web APIs 编辑
The DOM Node
interface is an abstract base class upon which many other DOM API objects are based, thus letting those object types to be used similarly and often interchangeably. As an abstract class, there is no such thing as a plain Node
object. All objects that implement Node
functionality are based on one of its subclasses. Most notable are Document
, Element
, and DocumentFragment
.
In addition, every kind of DOM node is represented by an interface based on Node
. These include Attr
, CharacterData
(which Text
, Comment
, and CDATASection
are all based on), ProcessingInstruction
, DocumentType
, Notation
, Entity
, and EntityReference
.
In some cases, a particular feature of the base Node
interface may not apply to one of its child interfaces; in that case, the inheriting node may return null
or throw an exception, depending on circumstances. For example, attempting to add children to a node type that cannot have children will throw an exception.
<div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/EventTarget" target="_top"><rect x="1" y="1" width="110" height="50" fill="#fff" stroke="#D4DDE4" stroke-width="2px" /><text x="56" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">EventTarget</text></a><polyline points="111,25 121,20 121,30 111,25" stroke="#D4DDE4" fill="none"/><line x1="121" y1="25" x2="151" y2="25" stroke="#D4DDE4"/><a xlink:href="https://developer.mozilla.org/wiki/en-US/docs/Web/API/Node" target="_top"><rect x="151" y="1" width="75" height="50" fill="#F4F7F8" stroke="#D4DDE4" stroke-width="2px" /><text x="188.5" y="30" font-size="12px" font-family="Consolas,Monaco,Andale Mono,monospace" fill="#4D4E53" text-anchor="middle" alignment-baseline="middle">Node</text></a></svg></div>
a:hover text { fill: #0095DD; pointer-events: all;}
Properties
In addition to the properties below, Node
inherits properties from its parent, EventTarget
.
Node.baseURI
Read only- Returns a
DOMString
representing the base URL of the document containing theNode
. Node.childNodes
Read only- Returns a live
NodeList
containing all the children of this node (including elements, text and comments).NodeList
being live means that if the children of theNode
change, theNodeList
object is automatically updated. Node.firstChild
Read only- Returns a
Node
representing the first direct child node of the node, ornull
if the node has no child. Node.isConnected
Read only- A boolean indicating whether or not the Node is connected (directly or indirectly) to the context object, e.g. the
Document
object in the case of the normal DOM, or theShadowRoot
in the case of a shadow DOM. Node.lastChild
Read only- Returns a
Node
representing the last direct child node of the node, ornull
if the node has no child. Node.nextSibling
Read only- Returns a
Node
representing the next node in the tree, ornull
if there isn't such node. Node.nodeName
Read only- Returns a
DOMString
containing the name of theNode
. The structure of the name will differ with the node type. E.g. AnHTMLElement
will contain the name of the corresponding tag, like'audio'
for anHTMLAudioElement
, aText
node will have the'#text'
string, or aDocument
node will have the'#document'
string. Node.nodeType
Read only- Returns an
unsigned short
representing the type of the node. Possible values are:Name Value ELEMENT_NODE
1
ATTRIBUTE_NODE
2
TEXT_NODE
3
CDATA_SECTION_NODE
4
ENTITY_REFERENCE_NODE
5
ENTITY_NODE
6
PROCESSING_INSTRUCTION_NODE
7
COMMENT_NODE
8
DOCUMENT_NODE
9
DOCUMENT_TYPE_NODE
10
DOCUMENT_FRAGMENT_NODE
11
NOTATION_NODE
12
Node.nodeValue
- Returns / Sets the value of the current node.
Node.ownerDocument
Read only- Returns the
Document
that this node belongs to. If the node is itself a document, returnsnull
. Node.parentNode
Read only- Returns a
Node
that is the parent of this node. If there is no such node, like if this node is the top of the tree or if doesn't participate in a tree, this property returnsnull
. Node.parentElement
Read only- Returns an
Element
that is the parent of this node. If the node has no parent, or if that parent is not anElement
, this property returnsnull
. Node.previousSibling
Read only- Returns a
Node
representing the previous node in the tree, ornull
if there isn't such node. Node.textContent
- Returns / Sets the textual content of an element and all its descendants.
Obsolete properties
Node.localName
Read only- Returns a
DOMString
representing the local part of the qualified name of an element.Note: In Firefox 3.5 and earlier, the property upper-cases the local name for HTML elements (but not XHTML elements). In later versions, this does not happen, so the property is in lower case for both HTML and XHTML.
Node.namespaceURI
Read only- The namespace URI of this node, or
null
if it is no namespace.Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the
http://www.w3.org/1999/xhtml/
namespace in both HTML and XML trees. Node.prefix
Read only- Is a
DOMString
representing the namespace prefix of the node, ornull
if no prefix is specified.
Methods
In addition to the properties below, Node
inherits methods from its parent, EventTarget
.
Node.appendChild(childNode)
- Adds the specified
childNode
argument as the last child to the current node.
If the argument referenced an existing node on the DOM tree, the node will be detached from its current position and attached at the new position. Node.cloneNode()
- Clone a
Node
, and optionally, all of its contents. By default, it clones the content of the node. Node.compareDocumentPosition()
- Compares the position of the current node against another node in any other document.
Node.contains()
- Returns a
Boolean
value indicating whether or not a node is a descendant of the calling node. Node.getBoxQuads()
- Returns a list of the node's CSS boxes relative to another node.
Node.getRootNode()
- Returns the context object's root which optionally includes the shadow root if it is available.
Node.hasChildNodes()
- Returns a
Boolean
indicating whether or not the element has any child nodes. Node.insertBefore()
- Inserts a
Node
before the reference node as a child of a specified parent node. Node.isDefaultNamespace()
- Accepts a namespace URI as an argument and returns a
Boolean
with a value oftrue
if the namespace is the default namespace on the given node orfalse
if not. Node.isEqualNode()
- Returns a
Boolean
which indicates whether or not two nodes are of the same type and all their defining data points match. Node.isSameNode()
- Returns a
Boolean
value indicating whether or not the two nodes are the same (that is, they reference the same object). Node.lookupPrefix()
- Returns a
DOMString
containing the prefix for a given namespace URI, if present, andnull
if not. When multiple prefixes are possible, the result is implementation-dependent. Node.lookupNamespaceURI()
- Accepts a prefix and returns the namespace URI associated with it on the given node if found (and
null
if not). Supplyingnull
for the prefix will return the default namespace. Node.normalize()
- Clean up all the text nodes under this element (merge adjacent, remove empty).
Node.removeChild()
- Removes a child node from the current element, which must be a child of the current node.
Node.replaceChild()
- Replaces one child
Node
of the current one with the second one given in parameter.
Obsolete methods
Node.getUserData()
- Allows a user to get some
DOMUserData
from the node. Node.hasAttributes()
- Returns a
Boolean
indicating if the element has any attributes, or not. Node.isSupported()
- Returns a
Boolean
flag containing the result of a test whether the DOM implementation implements a specific feature and this feature is supported by the specific node. Node.setUserData()
- Allows a user to attach, or remove,
DOMUserData
to the node.
Examples
Remove all children nested within a node
function removeAllChildren(element) {
while (element.firstChild) {
element.removeChild(element.firstChild)
}
}
Sample usage
/* Note: or use document.body.textContent = "" */
removeAllChildren(document.body)
Recurse through child nodes
The following function recursively calls a callback function for each node contained by a root node (including the root itself):
function eachNode(rootNode, callback) {
if (!callback) {
const nodes = []
eachNode(rootNode, function(node) {
nodes.push(node)
})
return nodes
}
if (false === callback(rootNode)) {
return false
}
if (rootNode.hasChildNodes()) {
const nodes = rootNode.childNodes
for (let i = 0, l = nodes.length; i < l; ++i) {
if (false === eachNode(nodes[i], callback)) {
return
}
}
}
}
Syntax
eachNode(rootNode, callback)
Description
Recursively calls a function for each descendant node of rootNode
(including the root itself).
If callback
is omitted, the function returns an Array
instead, which contains rootNode
and all nodes contained within.
If callback
is provided, and it returns Boolean
false
when called, the current recursion level is aborted, and the function resumes execution at the last parent's level. This can be used to abort loops once a node has been found (such as searching for a text node which contains a certain string).
Parameters
rootNode
- The
Node
object whose descendants will be recursed through. callback
Optional- An optional callback function that receives a
Node
as its only argument. If omitted,eachNode
returns anArray
of every node contained withinrootNode
(including the root itself).
Sample usage
The following example prints the textContent
properties of each <span>
tag in a <div>
element named "box"
:
<div id="box">
<span>Foo</span>
<span>Bar</span>
<span>Baz</span>
</div>
const box = document.getElementById("box")
eachNode(box, function(node) {
if (null != node.textContent) {
console.log(node.textContent)
}
})
The above will result in the following strings printing to the user's console:
"\n\t", "Foo", "\n\t", "Bar", "\n\t", "Baz"
Note: Whitespace forms part of a Text
node, meaning indentation and newlines form separate Text
between the Element
nodes.
Realistic usage
The following demonstrates a real-world use of the eachNode()
function: searching for text on a web-page.
We use a wrapper function named grep
to do the searching:
function grep(parentNode, pattern) {
const matches = []
let endScan = false
eachNode(parentNode, function(node){
if (endScan) {
return false
}
// Ignore anything which isn't a text node
if (node.nodeType !== Node.TEXT_NODE) {
return
}
if (typeof pattern === "string") {
if (-1 !== node.textContent.indexOf(pattern)) {
matches.push(node)
}
}
else if (pattern.test(node.textContent)) {
if (!pattern.global) {
endScan = true
matches = node
}
else {
matches.push(node)
}
}
})
return matches
}
For example, to find Text
nodes that contain typos:
const typos = ["teh", "adn", "btu", "adress", "youre", "msitakes"]
const pattern = new RegExp("\\b(" + typos.join("|") + ")\\b", "gi")
const mistakes = grep(document.body, pattern)
console.log(mistakes)
Specifications
Specification | Status | Comment |
---|---|---|
DOM The definition of 'Node' in that specification. | Living Standard | Added the following methods: getRootNode() |
DOM4 The definition of 'Node' in that specification. | Obsolete | Removed the following properties: attributes , namespaceURI , prefix , and localName .Removed the following methods: isSupported() , hasAttributes() , getFeature() , setUserData() , and getUserData() . |
Document Object Model (DOM) Level 3 Core Specification The definition of 'Node' in that specification. | Obsolete | The methods insertBefore() , replaceChild() , removeChild() , and appendChild() returns one more kind of error (NOT_SUPPORTED_ERR ) if called on a Document .The normalize() method has been modified so that Text node can also be normalized if the proper DOMConfiguration flag is set.Added the following methods: compareDocumentPosition() , isSameNode() , lookupPrefix() , isDefaultNamespace() , lookupNamespaceURI() , isEqualNode() , getFeature() , setUserData() , and getUserData(). Added the following properties: baseURI and textContent . |
Document Object Model (DOM) Level 2 Core Specification The definition of 'Node' in that specification. | Obsolete | The ownerDocument property was slightly modified so that DocumentFragment also returns null .Added the following properties: namespaceURI , prefix , and localName .Added the following methods: normalize() , isSupported() and hasAttributes() . |
Document Object Model (DOM) Level 1 Specification The definition of 'Node' in that specification. | Obsolete | Initial definition. |
Browser compatibility
BCD tables only load in the browser
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论