`
robinqu
  • 浏览: 88675 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

Javascript 寻找文档元素

阅读更多
Finding Elements in a Document
在文档中查找元素

引用
The document.documentElement property refers to the <html> tag that serves as the root element of the document.

the document.body property refers to the <body> tag which is more commonly useful than its <html> parent.

getElementsByTagName() selects the first element of the returned array.
if you pass the special string "15-" to getElementsByTagName(), it returns a list of all elements in the document, in the order in which they appear

This special usage is not supported in IE 5 and IE 5.5. See instead the IE-specific HTMLDocument.all[]

getElementById() retruns a Node
getElementByName() returns a NodeList



document.documentElement 对应HTML标签,是documeng的根元素
document.body对应body标签,这个比html标签更常用

document.getElementByTagName()返回节点列表,包含具有该标签的元素;传递"15-"可返回所有标签,但这个特性在IE5、IE5中不可用
document.getElementById()返回具有该ID的节点
document.getElementByName()返回节点列表,包含具有该name属性的节点元素


Modifying a Document
修改文档
引用

It is also possible to append, insert, delete, or replace text within a Text node with the appendData(), insertData(), deleteData(), and replaceData() methods.


appendChild()
createElement()
replaceChild()
setAttribute()
insertBefore()

以上方法可以实现追加子节点、创建元素、替换子节点、设置节点属性、前方插入节点等等;对应的还有对文字节点的数据替换、删除、附加等方法。

Working with Document Fragments
使用文档碎片
引用

A DocumentFragment is a special type of node that does not appear in a document itself but serves as a temporary container for a sequential collection of nodes and allows those nodes to be manipulated as a single object.

createDocumentFragment()

when you are ready to add those nodes to the document, add the DocumentFragment itself


文档碎片document fragments,是一种特殊的节点,它本身不显示在文档总,但可以作为一种临时的节点容器。待其子元素修改好后,可以将该文档碎片添加到文档中,其效果会是文档碎片的子元素保持其结构不变的被添加到指定位置,而文档碎片对象并不存在。
document.createDocumentFragement() 方法可以创建一个文档碎片对象


Adding Content to a Document
向文档中添加内容

Document.createElement()
Document.createTextNode()

Node.appendChild(), Node.insertBefore(), and Node.replaceChild()


innerHTML

引用
When you query the value of this property for an HTML element, what you get is a string of HTML text that represents the children of the element.

It turns out that using innerHTML is a reasonably efficient thing to do, especially when working with large chunks of HTML text to be parsed. Note, however that appending bits of text to the innerHTML property with the += operator is usually not efficient because it requires both a serialization step and a parsing step.


当读取一个HTML元素节点的innerHTML属性,你得到的是其所有子节点的HTML结构的代码。
当你处理大段的HTML代码,innerHTML属性是非常有用的。但注意+=操作符会让浏览器进行一个序列化操作和解析操作,这样会影响效率。


Element-creation utility functions
一个创建元素的工具函数:

/**
 * make(tagname, attributes, children):
 *   create an HTML element with specified tagname, attributes, and children.
 *
 * The attributes argument is a JavaScript object: the names and values of its
 * properties are taken as the names and values of the attributes to set.
 * If attributes is null, and children is an array or a string, the attributes
 * can be omitted altogether and the children passed as the second argument.
 *
 * The children argument is normally an array of children to be added to
 * the created element. If there are no children, this argument can be
 * omitted. If there is only a single child, it can be passed directly
 * instead of being enclosed in an array. (But if the child is not a string
 * and no attributes are specified, an array must be used.)
 *
 * Example: make("p", ["This is a ", make("b", "bold"), " word."]);
 *
 * Inspired by the MochiKit library (http://mochikit.com) by Bob Ippolito
 */
function make(tagname, attributes, children) {

    // If we were invoked with two arguments, the attributes argument is
    // an array or string; it should really be the children arguments.
    if (arguments.length == 2 &&
        (attributes instanceof Array || typeof attributes == "string")) {
        children = attributes;
        attributes = null;
    }

    // Create the element
    var e = document.createElement(tagname);

    // Set attributes
    if (attributes) {
        for(var name in attributes) e.setAttribute(name, attributes[name]);
    }

    // Add children, if any were specified.
    if (children != null) {
        if (children instanceof Array) {  // If it really is an array
            for(var i = 0; i < children.length; i++) { // Loop through kids
                var child = children[i];
                if (typeof child == "string")          // Handle text nodes
                    child = document.createTextNode(child);
                e.appendChild(child);  // Assume anything else is a Node
            }
        }
        else if (typeof children == "string") // Handle single text child
            e.appendChild(document.createTextNode(children));
        else e.appendChild(children);         // Handle any other single child
    }

    // Finally, return the element.
    return e;
}

/**
 * maker(tagname): return a function that calls make() for the specified tag.
 * Example: var table = maker("table"), tr = maker("tr"), td = maker("td");
 */
function maker(tag) {
    return function(attrs, kids) {
        if (arguments.length == 1) return make(tag, attrs);
        else return make(tag, attrs, kids);
    }
}



Details about related Methods
相关方法的简介

Document.getElementById( ): find an element with the specified unique ID
Element getElementById(String elementId);
elementId : The value of the id attribute of the desired element.
Returns : The Element node that represents the document element with the specified id attribute or null if no such element is found.

Document.getElementsByTagName( ): return all Element nodes with the specified name
Element[] getElementsByTagName(String tagname);
tagname : The tag name of the Element nodes to be returned, or the wildcard string "*" to return all Element nodes in the document regardless of tag name. For HTML documents, tag names are compared in a case-insensitive fashion. (Prior to version 6, IE does not support this wildcard syntax.)
Returns : A read-only array (technically, a NodeList) of all Element nodes in the document tree with the specified tag name. The returned Element nodes are in the same order in which they appear in the document source. The NodeList is "live"i.e., its contents are automatically updated as necessary if elements with the specified tag name are added to or removed from the document.

HTMLDocument.getElementsByName( ): find elements with the specified name attribute
Element[] getElementsByName(String elementName);
elementName : The desired value for the name attribute.
Returns : A read-only array (technically a NodeList) of Element objects that have a name attribute with the specified value. If no such elements are found, the returned array is empty and has a length of 0.

Document.createComment( ): create a new Comment node
Comment createComment(String data);
data : The text of the Comment node to create.
Returns : A newly created Comment node, with the specified data as its text

Document.createDocumentFragment( ): create a new, empty DocumentFragment node
DocumentFragment createDocumentFragment( );
Returns : A newly created DocumentFragment node with no children.

Document.createElement( ): create a new Element node
Element createElement(String tagName)
    tHRows DOMException;
tagName : The tag name of the Element to be created. Since HTML tags are case-insensitive, you may use any capitalization for HTML tag names. XML tag names are case-sensitive.
Returns : A newly created Element node with the specified tag name.
Throws : This method throws a DOMException with a code of INVALID_CHARACTER_ERR if tagName contains an illegal character.

Document.createTextNode( ): create a new Text node
Text createTextNode(String data);
data: The content of the Text node.
Returns: A newly created Text node that represents the specified data string.

Node: a node in a document tree
Subinterfaces: Attr, CDATASection, CharacterData, Comment, Document, DocumentFragment, DocumentType, Element, ProcessingInstruction, Text
Constants:
Node.ELEMENT_NODE = 1;                 // Element
Node.ATTRIBUTE_NODE = 2;               // Attr
Node.TEXT_NODE = 3;                    // Text
Node.CDATA_SECTION_NODE = 4;           // CDATASection
Node.PROCESSING_INSTRUCTION_NODE = 7;  // ProcessingInstruction
Node.COMMENT_NODE = 8;                 // Comment
Node.DOCUMENT_NODE = 9;                // Document
Node.DOCUMENT_TYPE_NODE = 10;          // DocumentType
Node.DOCUMENT_FRAGMENT_NODE = 11;      // DocumentFragment
Properties
readonly Attr[] attributes
readonly Node[] childNodes
readonly Node firstChild
readonly Node lastChild
readonly Node nextSibling
readonly String nodeName
String nodeValue
readonly Node parentNode
readonly Node previousSibling

All objects in a document tree (including the Document object itself) implement the Node interface, which provides the fundamental properties and methods for traversing and manipulating the tree.

Node.appendChild( ): insert a node as the last child of this node
Node appendChild(Node newChild)
    tHRows DOMException;
newChild: The node to be inserted into the document. If the node is a DocumentFragment, it is not directly inserted, but each of its children are.
Returns: The node that was added.
Throws: This method may throw a DOMException with one of the following code values in the following circumstances: HIERARCHY_REQUEST_ERR, WRONG_DOCUMENT_ERR, NO_MODIFICATION_ALLOWED_ERR

Node.cloneNode( ): duplicate a node and, optionally, all of its descendants
Node cloneNode(boolean deep);
deep: If this argument is TRue, cloneNode( ) recursively clones all descendants of this node. Otherwise, it clones only this node.
Returns: A copy of this node.


Node.insertBefore( ): insert a node into the document tree before the specified node
Node insertBefore(Node newChild,
                  Node refChild)
    throws DOMException;
newChild: The node to be inserted into the tree. If it is a DocumentFragment, its children are inserted instead.
refChild: The child of this node before which newChild is to be inserted. If this argument is null, newChild is inserted as the last child of this node.
Returns: The node that was inserted.

This method inserts the node newChild into the document tree as a child of this node. The new node is positioned within this node's childNodes[] array so that it comes immediately before the refChild node. If refChild is null, newChild is inserted at the end of childNodes[], just as with the appendChild( ) method. Note that it is illegal to call this method with a refChild that is not a child of this node.

Node.removeChild( ): remove (and return) the specified child of this node
Node removeChild(Node oldChild)
    tHRows DOMException;
oldChild: The child node to remove.
Returns: The node that was removed.

Node.replaceChild( ): replace a child node with a new node
Node replaceChild(Node newChild,
                  Node oldChild)
    throws DOMException;
newChild: The replacement node.
oldChild: The node to be replaced.
Returns: The node that was removed from the document and replaced.
This method replaces one node of the document tree with another. oldChild is the node to be replaced and must be a child of this node. newChild is the node that takes its place in the childNodes[] array of this node.

Element.getAttribute( ): return the string value of a named attribute
String getAttribute(String name);
name: The name of the attribute whose value is to be returned.
Returns: The value of the named attribute as a string. If the attribute is not defined, this method is supposed to return an empty string. Some implementations return null in this case, however.

Element.removeAttribute( ): delete a named attribute of an element
void removeAttribute(String name);
name: The name of the attribute to be deleted.
Throws: This method may throw a DOMException with a code of NO_MODIFICATION_ALLOWED_ERR if this element is read-only and does not allow its attributes to be removed.

Element.setAttribute( ): create or change an attribute of an element
void setAttribute(String name,
                  String value)
    throws DOMException;
name: The name of the attribute to be created or modified.
value: The string value of the attribute.

This method sets the specified attribute to the specified value. If no attribute by that name already exists, a new one is created.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics