JavascriptReference(2)-DOM

 
Brief: This article explains/lists DOM properties and methods. That is true you can refer most of them in your JavaScript.
DOM (Document Object Model) Reference
The DOM (Document Object Model) gives you generic access to most elements, their styles and attributes in a document. This is a no-nonsense, easy to follow DOM reference for JavaScript.
Whenever you have to attend the DOM is different from document;
In DOM, there are :
Context
l         DOM Document Object Reference
l         DOM Elements Object reference
l         DOM Window Reference
l         DOM Event Object reference
l         DOM Style Reference
l         DOM Table Reference
l         Miscellaneous
1.1) DOM Document Object Reference
Document Object properties
Properties
Description
body
References the body element of the page. From there, you can then access other nodes contained within the body.
body.offsetWidth, body.offsetHeight
Returns the width and height of the entire document, respectively.
compatMode
Returns the compatibility mode of the current document, specifically, whether the page is rendered in Quirks or Stricts mode. The two possible values returned are "BackCompat" for Quirks and "CSS1Compat" for Strict. Useful for determining the doctype setting of the page and executing different code accordingly.
Example(s):
if (document.compatMode=="CSS1Compat")
// execute code for page with a valid doctype
doctype
Read-only property that returns the Document Type Definition (DTD) of the current document, or null if the page doesn't contain a DTD. Not supported in IE as of IE6.
documentElement
References the root element of the document, in the case of HTML documents, the html element. This read only property is useful for accessing all elements on the page, such as the HEAD.
Example(s):
entiredoc = document.documentElement;
var docnodes=entiredoc.childNodes
for (i=0; i<docnodes.length; i++)
alert(docnodes[i].tagName)
domain
Gets/sets the domain of the current document. Useful in cross domain scripting when one domain is to communicate with another.
Example(s):
document.domain="javascriptkit.com"
implementation
Returns the DOM implementation of the current document.
ownerDocument
Returns a reference to the document object that contains the current element/node.
var ownerdoc=document.getElementById("adiv").ownerDocument
readyState
IE exclusive property that specifies the loading status of the document. It returns one of the below 4 values:
1) uninitialized- The document hasn't started loading yet.
2) loading- The document is loading.
3) interactive- The document has loaded enough whereby user can interact with it.
4) complete- The document has fully loaded.
styleSheets[]
An array referencing all stylesheet objects on the page, whether they are defined using the <style> or <link> tag.
title
Specifies the title of the document. Read/write in modern browsers.
URL
A string that specifies the complete URL of the document.
Document object methods
Methods
Description
createAttribute("attributename")
Creates a new attribute, ready to be inserted somewhere in the document. It returns a reference to the created attribute.
Example(s):
var styleattr=document.createAttribute("align")
styleattr.nodeValue="center"
document.getElementById("sister").setAttributeNode(styleattr)
createComment(commenttext)
Creates an instance of the comment node. Once created, you can then insert it into the document tree using appendChild(), for example.
Example(s):
var commentnode=document.createComment("Copyright JavaScript Kit")
document.getElementById("mydiv").appendChild(commentnode)
createDocumentFragment()
Creates an empty document fragment. The result is a temporary container for creating and modifying new elements or attributes before introducing the final result to your document tree. This is a very useful method when you're performing multiple operations that add to or modify the document tree. Instead of directly modifying the document tree each time (very inefficient), it's much better to use a temporary "whiteboard" that is created by createDocumentFragment() to perform all your operations on first before finally inserting the result to the document tree.
Example(s):
<div id="sister"></div>

<script type="text/javascript">
var docfrag=document.createDocumentFragment()
var mydiv=document.createElement("div")
var divtext=document.createTextNode("This is div text")
mydiv.appendChild(divtext)
docfrag.appendChild(mydiv)
document.getElementById("sister").appendChild(docfrag) //div now reads "this is div text"
</script>
createElement(tagName)
Creates an instance of the element object, which can then added to the document tree using appendChild(), for example.
Example(s):
var textblock=document.createElement("p")
textblock.setAttribute("id", "george")
textblock.setAttribute("align", "center")
document.body.appendChild(textblock)
createTextNode(text)
Creates a new text node, which can then be added to an element in the document tree.
Example(s):
var headertext=document.createTextNode("Welcome to JavaScript Kit")
document.getElementById("mytitle").appendChild(headertext)
getElementById(id)
Accesses any element on the page via its ID attribute. A fundamental method within the DOM for accessing elements on the page.
getElementsByName(name)
Returns an array of elements with a name attribute whose value matches that of the parameter's. In IE6, elements with an ID attribute of the matching value will also be included in the array, and getElementsByName() is limited to retrieving form objects such as checkboxes and INPUT. In Firefox, nither of these "pitfalls" apply.
<div name="george">f</div>
<div name="george">f</div>

<script type="text/javascript">
var georges=document.getElementsByName("george")
for (i=0; i< georges.length; i++)
// do something with each DIV tag with name="george". Firefox only.
</script>
getElementsByTagName(tagname)
Returns an array of elements whose tag name matches the parameter. In Firefox/ IE6+, you may enter an asterisk ("*") as the parameter to retrieve a list of all elements within the document.
var ptags=document.getElementsByTagName("p")
var alltags=document.getElementsByTagName("*") //returns all elements on page
 
1.2) DOM Element Object Reference
DOM Element properties
DOM properties that can be used on most elements in a document:
Properties
Description
attributes[]
Returns an array (NamedNodeMap) containing all the attributes defined for the element in question, including custom attributes. IE6 returns not just attributes explicitly defined by the webmaster, but those of the element's internal DTD as well. In Firefox, attributes[] work more as expected, returning only user defined attributes, and even reflect changes done by scripting to an attribute.
Each attribute[] element returned supports a name and value property to retrieve additional information about the attribute.
Example(s):
var imageattributes=document.getElementById("myimage").attributes

imageattributes[0].name //name of the first attribute of "myimage"

imageattributes[0].value //value of the first attribute of "myimage"

imageattributes.getNamedItem("src").value //value of the "src" property of "myimage"
childNodes[]
Returns an array of all of the child nodes of an element as objects. Use the properties "nodeName" and "nodeType" to retrieve additional information about a node.
Example(s):
//access some <ul> element
var mylist=document.getElementById("mylist")
for (i=0; i<mylist.childNodes.length; i++){
if (mylist.childNodes[i].nodeName=="LI")
//do something
}
className
Returns the CSS class attribute of an element. Read/write.
Example(s):
document.getElementById("test").className="class1" //Assign the class "class1" to element

document.getElementById("test").className+=" class2" //Assign an additional "class2" class to element
clientWidth
A cross browser (NS7+, IE4+) property that returns the viewable width of the content on the page, not including borders, margins, or scrollbars (overflowing content).
Example(s):
var pagewidth=document.body.clientWidth
clientHeight
A cross browser (NS7+, IE4+) property that returns the viewable height of the content on the page, not including borders, margins, or scrollbars (overflowing content).
dir
Read/write property that returns the text direction of the element. Valid values are "ltr" (left to right) and "rtl" (right to left). Default is "ltr."
Example(s):
document.getElementById("mydiv").dir="rtl" //change text direction
firstChild
Returns a reference to the first child of an element.
id
Read/write property that reflects the ID attribute of an element. Use this property to access any element on the page easily.
innerHTML
A cross browser (non W3C DOM) property that lets you easily change the HTML contents of an element. Generally this property can only be invoked after the document has fully loaded.
Example(s):
<p><b>Old paragraph text</b></p>
<script type="text/javascript">
window.οnlοad=function(){
document.getElementsByTagName("p")[0].innerHTML="<b>new paragraph text</b>"
}
</script>
lang
Read/write property that specifies the language of an element's attribute values and text content. Commonly invoked on the body level to determine the base language of the document.
lastChild
Returns a reference to the last child of an element.
localName
Returns the name of the node of an XML element. Equivilant to the nodeName property for regular HTML elements.
namespaceURI
Returns the URI string assigned to the xmlns attribute of an XML element.
nextSibling
Returns the next node following the current one. Returns null if there are none or for text nodes inside an element.
nodeName
Returns a string indicating the name of the node, in the case of elements, its tag name. Returned value is in uppercase.
Example(s):
if (document.getElementById("test").firstChild.nodeName=="DIV")
alert("This is a DIV")
nodeType
Returns an integer indicating the type of a node. See chart for what each integer value represents.
Example(s):
alert(document.getElementById("adiv").nodeType) //DIV element. Alerts 1
nodeValue
Read/write property that reflects the value of a node. For text nodes, the content of the node is returned, while for attribute nodes, the attribute value. Null is returned for Document and element nodes. Use this property to alter the contents of a text or attribute node.
Example(s):
<body>
<div id="test">Old text</div>

<script type="text/javascript">
if (document.getElementById("test").firstChild.nodeName=="#text")
document.getElementById("test").firstChild.nodeValue="New text"

</script>
offsetLeft
Gets the horizontal offset position of the current element relative to its offset container. Read only. Use "offsetParent" to determine what an element's container is. Typically a positioned DIV or TABLE will act as an offset container to any element contained inside them.
offsetTop
Gets the vertical offset position of the current element relative to its offset container. Read only. Use "offsetParent" to determine what an element's container is.
offsetParent
Returns the offset container of the current element. For most elements on the page, the "BODY" is their offset container. However, a positioned DIV for example creates its own offset container space.
Example(s):
<body>
<div id="master" style="position: relative">
<div id="slave" style="position: relative">test</div>
</div>

<script type="text/javascript">
alert(document.getElementById("slave").offsetParent.id) //alerts "master"
</script>
offsetWidth
A cross browser (non W3C DOM) property that returns the width of the element, including borders and padding if any, but not margins. In IE6, if a valid doctype is not specified, margins/padding are NOT included in the returned value.
offsetHeight
A cross browser (non W3C DOM) property that returns the height of the element, including borders and padding if any, but not margins. In IE6, if a valid doctype is not specified, margins/padding are NOT included in the returned value.
ownerDocument
Returns the document object that contains the current node.
parentNode
References the node that is the parent of the current one in the document tree.
prefix
Returns the namespace prefix of the current XML node, or null if not available.
previousSibling
Returns the previous node relative the current one in the document tree. Returns null if there are none or for text nodes inside an element.
scrollLeft
A cross browser (NS7+, IE4+) property that returns the distance between the actual left edge of the element and its left edge currently in view. In a horizontally scrollable DIV for example, as you drag the scrollbar to the right, the DIV's scrollLeft property increases as the distance between its actual left edge and visible left edge increases. Applicable to scrollable elements, such as a DIV with scrollbars, a textarea, the BODY etc.
scrollTop
A cross browser (NS7+, IE4+) property that returns the distance between the actual top edge of the element and its top edge currently in view. Most commonly invoked on the BODY element for the purpose of positioning an element on the page so it's always visible.
Example(s):
<div id="static" style="width:150px; height:150px; position: absolute; border:1px solid yellow; left: 5px;">Some text</div>


<script type="text/javascript">
//Keep "static" always in view on the page
setInterval("document.getElementById('static').style.top=document.body.scrollTop+10+'px'", 50)
</script>
scrollHeight
A cross browser (NS7+, IE4+) property that returns the entire height of an element, including any area that may be hidden due to scrollbars. When the element does not contain vertical scrollbars, its scrollHeight is equal to its clientHeight.
scrollWidth
A cross browser (NS7+, IE4+) property that returns the entire width of an element, including any area that may be hidden due to scrollbars. When the element does not contain horizontal scrollbars, its scrollWidth is equal to its clientWidth.
style
References the style object of an element, in turn accessing and modifying individual style attributes' values.
Example(s):
document.getElementById("test").style.backgroundColor="yellow"
tabIndex
Gets/sets the tab order of the current element.
tagName
Returns the name of the tag of an element as a string and in uppercase.
title
Read/write property that returns the title of the document or "title" attribute of an element when invoked on an element.
 
DOM Element methods
Below lists the DOM methods that can be used on most elements in a document:
Properties
Description
addEventListener(eventType, listener, useCapture)
Associates a function with a particular event and binds the event to the current node. NS/Firefox only. addEventListener() accepts the following 3 parameters:
1) EventType: A string representing the event to bind, without the "on" prefix. For example, "click", "mousedown" etc.
2) listener: The function or method to associate with the event.
3) useCapture: Boolean indicating whether to bind the event as it is propogating towards the target node, (event Capture), or as the event bubbles upwards from the target (event bubble). Set to true or false, respectively.
The advantage of using the DOM to bind an event is that you can assign multiple functions to a node for the same event (ie: window.onload) without running into event handler conflicts.
Example(s):
function statusreport(){
alert("document has loaded")
}

if (window.addEventListener)
window.addEventListener("load", statusreport, false) //invoke function
window.οnlοad=statusreport() //function invoked again, since no event handler conflicts
attachEvent(eventType, function)
The IE5+ proprietary equivalent of addEventListener(). Note that for the parameter eventType, the even string should include the "on" prefix (ie: "onload", "onclick" etc).
Example(s):
if (window.attachEvent)
window.attachEvent("onload", statusreport) //invoke function
appendChild(node)
Inserts the specified node at the end of the current node object. A frequently used method for dynamically appending a new element or text to the document.
Example(s):
<div id="test"></div>
<script type="text/javascript">
var newdiv=document.createElement("div")
var newtext=document.createTextNode("A new div")
newdiv.appendChild(newtext) //append text to new div
document.getElementById("test").appendChild(newdiv) //append new div to another div
</script>
Blur()
Removes keyboard focus from the current element. Used for example to fire the onBlur event handler of an element via scripting.
click()
Executes a click on a element. Used for example to fire the onClick event handler of an element via scripting.
cloneNode(deepBoolean)
Duplicates and returns a copy of the current node as a standalone node (not part of document tree). Cloning a node copies both the original's attributes and values, including the ID attribute, so be sure to alter the cloned ID attribute's value so it's unique before introducing it to the document tree. This method supports a single Boolean parameter, "deepBoolean" that when set to true, clones all the sub nodes of the current node as well, such as any text contained within.
Example(s):
p=document.getElementById("mypara")
pclone = p.cloneNode(true)
detachEvent(eventType, function)
Removes an event handler and its function previously associated with a node in IE5+, via attachEvent() for example. The IE5+ proprietary equivalent of DOM2's removeEventListener().
Example(s):
if (window.detachEvent)
window.detachEvent("onload", statusreport) //invoke function
dispatchEvent(eventObject)
Dispatches an event to fire on a node artificially. This method returns a Boolean indicating whether any of the listeners which handled the event called preventDefault (false if called, otherwise, true). IE's equivalent of dispatchEvent() is fireEvent().
Example(s):
<div id="test" οnclick="alert('hi')">Sample DIV.</div>
<script type="text/javascript">
//Generate an artificial click event on "test". Fires alert("hi")
var clickevent=document.createEvent("MouseEvents")
clickevent.initEvent("click", true, true)
document.getElementById("test").dispatchEvent(myevent)
</script>
focus()
Sets focus on the current node.
getAttribute(attributeName)
Returns the value of the attribute named attribute of the current node.
Example(s):
document.getElementById("test").getAttribute("align")
getAttributeNS(namespace, localname)
Returns the value of the attribute with the given local name and namespace. Applicable in XML documents.
getAttributeNode(attributename)
Returns/references the attribute of the current element as a stand only node (not part of document tree).
Example(s):
var attributeobj=document.getElementById("nav").getAttributeNode("align")
attributeobj.value="center"
getAttributeNodeNS(namespace, localname)
Returns/references the attribute of the current element with the given local name and namespace. Applicable in XML documents.
getElementsByTagName(tagName)
Returns as an array all the child elements of the current element matching the "tagName" parameter (ie: "li"). In Firefox/ IE6+, you may enter an asterisk ("*") for the method's parameter to retrieve a list of all elements within the current.
Example(s):
var mylist=document.getElementById("navlist")
var listitems= mylist.getElementsByTagName("li")
for (i=0; i<listitems.length; i++)
//manipulate each li element
var alltags=document.getElementsByTagName("*") //returns all elements on page
getElementsByTagNameNS(namespace, localname)
Returns as an array all the child elements of the current element with the given local name and namespace. Applicable in XML documents.
hasAttribute(attributename)
Returns a Boolean value indicating whether the current element contains an attribute (ie: "align").
Example(s):
if (document.getElementById("mytable").hasAttribute("style"))
//manipuate the element's style
hasAttributeNS(namespace, localname)
Returns a Boolean value indicating whether the current element contains an attribute with the given local name and namespace. Applicable in XML documents.
hasAtrributes()
Returns a Boolean value indicating whether the current element has any explicit attributes defined.
hasChildNodes()
Returns a Boolean value indicating whether the current element contains any child nodes.
insertBefore(newElement, targetElement)
Updated. Inserts a new node "newElement" as a child node of the current node. The "targetElement" property dictates where "newElement" is inserted within the list of child nodes. If set to null, the new element is inserted as the last child node; otherwise, it's inserted right before "targetElement".
Example(s):
<div id="employees">
<div id="george">George Doe: Human resources department</div>
</div>
To insert a new DIV directly above "george", so the outcome becomes:
<div id="employees">
<div id='kevin">Kevin Lin: Main system administrator</div>
<div id="george">George Doe: Human resources department</div>
</div>
You would do the following:
<script type="text/javascript">
var newemployee=document.createElement("div")
var oldemployee=document.getElementById("george")
newemployee.setAttribute("id", "kevin")
newemployee.innerHTML="Kevin Lin: Main system administrator"
document.getElementById("employees").insertBefore(newemployee, oldemployee)
</script>
Important: Like many DOM methods that change the structure of the document, insertBefore() can only be called after the page has fully loaded. Doing so before will return strange errors in most browsers!
 
insertAfter(newElement, targetElement)
Updated. As of DOM Level 2 there does NOT exist an insertAfter() method. However, it can be easily simulated using insertBefore() above. For the "targetElement" parameter, just use "targetElement.nextSibling" instead.
<div id="employees">
<div id="george">George Doe: Human resources department</div>
</div>
To insert a new DIV directly below "george", so the outcome becomes:
<div id="employees">
<div id="george">George Doe: Human resources department</div>
<div id='kevin">Kevin Lin: Main system administrator</div>
</div>
You would do the following:
<script type="text/javascript">
var newemployee=document.createElement("div")
var oldemployee=document.getElementById("george")
newemployee.setAttribute("id", "kevin")
newemployee.innerHTML="Kevin Lin: Main system administrator"
document.getElementById("employees").insertBefore(newemployee, oldemployee.nextSibling)
</script> 
item(index)
Retrieves a node based on its index within the document tree. IE4+ and FireFox1+.
Example(s):
<div id="div1"></div>
<div id="div2"></div>
<script type="text/javascript">
var mydivs=document.getElementsByTagName("div");
alert(mydivs.item(1).id) //alerts "div2"
</script>
normalize()
Normalizes the current node and its sub tree. See here for more info.
removeAttribute(attributename)
Removes an attribute by its name.
Example(s):
document.getElementById("test").removeAttribute("href")
removeAttributeNode(attributereference)
Remove an attribute by passing in as parameter a reference to the attribute object to remove. It offers an alternate way to removeAttribrute()"for removing attributes, when all you have is a reference to the attribute object in your script.
Example(s):
var hrefattr=document.getElementById("test").getAttributeNode("href")
document.getElementById("test").removeAttributeNode(hrefattr)
removeAttributeNS(namespace, localname)
Removes an attribute with the specified namespace and localname.
removeChild(childreference)
Removes the child node of the current node. The removed node can then be reinserted elsewhere in the document tree.
Example(s):
<div id="father"><div id="child">A child</div></div>
<script type="text/javascript">
var childnode=document.getElementById("child")
var removednode=document.getElementById("father").removeChild(childnode)
</script>
removeEventListener(eventType, listener, useCapture)
Removes the specified event from being binded to the current node:
1) EventType: A string representing the event to unbind, without the "on" prefix. For example, "click", "mousedown" etc.
2) listener: The function or method to associate with the event.
3) useCapture: Boolean indicating whether to unbind the event as it is propagating towards the target node, (event Capture), or as the event bubbles upwards from the target (event bubble). Set to true or false, respectively.
 NS6/Firefox method.
replaceChild(newChild, oldChild)
Replaces one child node of the current node with another child node.
Example(s):
<div id="adiv"><span id="innerspan"></span></div>
<script type="text/javascript">
var oldel=document.getElementById("innerspan")
var newel=document.createElement("p")
document.getElementById("adiv").replaceChild(newel, oldel)
</script>
scrollIntoView([Boolean])
Firefox/IE4+ proprietary method that scrolls an element into view. It accepts an optional Boolean parameter that when set to true (default), scrolls the element so its top left corner touches the top of the viewable window. If false, the element's bottom left corner touches the bottom of the window.
setAttribute(attributename, value, [iecaseflag])
Sets an attribute's value for the current element. If the attribute doesn't exit yet, it creates the attribute first. Otherwise, the existing attribute is modified with the new value. In IE, the following two pitfalls exist:
To set the "class" attribute, use "className" instead.
The "attributename" parameter is case sensitive by default in IE . This means if you attempt to set the "align" attribute and "Align" already exists on the element, both will be present as a result. To turn off case sensitivity, set the IE-only 2nd parameter of setAttribute() to 0 (instead of default, which is 1).
Example(s):
document.getElementById("test").setAttribute("title", "JavaScript Kit")
setAttributeNS(namespace, qualifiedname, value)
Sets or creates an attribute for the current node with the given local name and namespace. Applicable in XML documents.
setAttributeNode(attributereference)
Sets or creates an attribute for the current node. "attributereference" should be a reference to a attribute you wish to insert. If an attribute of the same name (as referenced) already exists on the node, it is replaced with the newly inserted one.
Example(s):
<div id="brother" style="border:1px solid black; padding: 2px">Brother</div>
<div id="sister">Sister</div>

<script type="text/javascript">
var bro=document.getElementById("brother")
var sis=document.getElementById("sister")
var brostyle=bro.getAttributeNode("style")
var clonebrostyle=brostyle.cloneNode(false) //clone attribute first. Required.
sis.setAttributeNode(clonebrostyle)
</script>
supports(feature, [version])
Tests to see if this DOM implementation supports a particular feature.
 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值