`
robinqu
  • 浏览: 90293 次
  • 性别: 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.
分享到:
评论

相关推荐

    JavaScript版本植物大战僵尸(源码,使用文档)

    JavaScript中的DOM(Document Object Model)是另一个关键概念,用于描述HTML或XML文档的结构。在游戏中,每个植物、僵尸和道具都是一个DOM元素,可以通过JavaScript操作它们的位置、属性和样式,实现动画效果和游戏...

    javascript 经典实例大全一

    JavaScript,作为全球最广泛使用的客户端脚本语言,是构建网页动态功能和交互效果的核心技术。在"JavaScript 经典实例...无论是想要深入理解JavaScript,还是寻找解决问题的灵感,这个压缩包都提供了丰富的学习材料。

    lianliankan_javascript.rar

    DOM是HTML和XML文档的结构化表示,JavaScript通过DOM可以对网页内容进行读取、修改和添加。在这个连连看游戏中,每个可点击的方块在HTML中可能对应一个特定的元素,JavaScript通过获取和修改这些元素的属性来实现...

    一个JavaScript库让文件能够拖放到任何HTML元素上

    标题中的“一个JavaScript库让文件能够拖放到任何HTML元素上”指的是使用JavaScript库来实现HTML5的拖放功能,使得用户可以通过鼠标拖动文件到指定的HTML元素(如div、input等)上,从而实现文件上传或其他交互操作...

    javascript 2048小游戏

    2. **DOM操作**:JavaScript用于动态修改HTML元素,显示和更新游戏状态。 3. **CSS动画**:可能使用CSS3动画或JavaScript实现方块的移动效果。 4. **数据结构**:游戏可能使用二维数组来存储和操作方块,理解数组...

    JavaScript获取DOM元素的11种方法总结

    接下来,通过父节点获取元素的方法允许我们利用已知的父节点来寻找子节点,无论是在整个文档中还是在指定的父节点下。 1. 获取第一个子节点:`parentObj.firstChild`方法返回指定父节点的第一个子节点。如果要获取...

    JavaScript_一系列与MDN web组件文档相关的web组件示例.zip

    本资源“JavaScript_一系列与MDN web组件文档相关的web组件示例.zip”聚焦于JavaScript的一个重要领域——Web组件,这是一个允许开发者创建可重用、自包含且独立于库或框架的自定义HTML元素的技术。 Web组件是现代...

    web开发javascript,css,jquery,php,sql等开发文档

    在Web开发领域,JavaScript、CSS、jQuery、PHP和SQL是不可或缺的核心技术。这些技术相互协作,构建出功能丰富、...这个压缩包文件提供了关于这些技术的开发文档,可以帮助开发者节省寻找资料的时间,集中精力提升技能。

    JS特效大全JavaScript特效

    这个资源特别适合初学者作为实战练习,同时也适合有经验的开发者寻找灵感。无论你是要创建一个动态网站,还是想提升自己的前端技能,"JS特效大全JavaScript特效"都是一个宝贵的资料库。通过深入学习和实践其中的每个...

    JavaScript 参考手册.zip

    JavaScript是一种广泛应用于网页和网络应用的脚本语言,主要由Netscape公司的Brendan Eich...无论你是想要深入理解JavaScript,还是在实际项目中寻找解决方案,这个"JavaScript 参考手册.zip"都将是你不可或缺的工具。

    javascript编写的迷宫小游戏

    8. **DOM操作**:为了在网页上展示迷宫和相关信息,JavaScript需要操作DOM(文档对象模型),更新特定元素的内容或样式。 9. **性能优化**:由于迷宫游戏可能涉及大量的计算,优化代码性能是必要的。这可能包括减少...

    javascript游戏24点源码

    JavaScript可以使用DOM API来读取、修改或创建文档元素。在这个游戏中,JavaScript可能用于获取用户界面的输入值,更新显示结果,或者改变页面元素的状态。 3. **数据存储**:游戏中的数字卡片可能被存储在...

    JavaScript实现获取某个元素相邻兄弟节点的prev与next方法

    在JavaScript中,DOM(Document Object Model)模型是用于表示HTML或XML文档的一种树形结构,它允许我们通过JavaScript来操作页面中的元素。本篇将详细解释如何使用JavaScript获取某个元素的相邻兄弟节点,并介绍`...

    W3Cfuns_JavaScript_DOM编程艺术

    5. **遍历与查找**:DOM提供多种方法来遍历文档树,寻找特定节点。如父母节点、子节点、兄弟节点的查找,以及XPath和CSS选择器的使用,帮助开发者高效地定位元素。 6. **AJAX**:随着Web应用的复杂性增加,AJAX...

    gtk3api文档html离线阅读

    尽管缺失了部分JavaScript和CSS样式文件,但据描述所述,这应该不会对基本的阅读和使用造成太大影响。 Gtk3是Gnome桌面环境下的一个主要的图形用户界面库,用于构建跨平台的GUI应用程序。它基于GTK+库,且版本3引入...

    javascript代码和网页演示

    例如,DOM(文档对象模型)操作允许我们查找、修改或添加HTML元素,使网页具备动态性。通过学习这些示例,我们可以掌握如何使用`document.getElementById`、`document.createElement`、`addEventListener`等方法来...

    javascript完全自学手册

    - **官方文档**:阅读ECMAScript标准规范和MDN(Mozilla Developer Network)文档,获取权威的JavaScript知识和最新的技术信息。 - **在线课程和教程**:网上的教程和课程通常提供循序渐进的学习路径,对于初学者...

    HTML脚本大全常用Javascript特效代

    JavaScript通过DOM可以访问和修改网页元素。例如,通过`document.getElementById()`、`document.querySelector()`或`document.querySelectorAll()`选取元素,然后改变其样式、内容或位置。 三、事件处理 JavaScript...

    showdoc开发搭建文档

    通过Showdoc,你可以创建层次分明的目录结构,添加表格、图片、代码块等元素,使得文档内容更加丰富。 在二次开发方面,"showdoc-master"这个文件名暗示了这是一个Git仓库的主分支,通常包含源代码、配置文件和文档...

    简述JavaScript对传统文档对象模型的支持

    在JavaScript早期版本中引入的传统DOM模型,允许我们访问和操作文档中的表单、表单元素以及图像等关键部分。它提供了一系列的只读属性(例如,title、URL和lastModified),这些属性能够帮助我们获取有关整个文档的...

Global site tag (gtag.js) - Google Analytics