Categories:

JavaScript Kit > DOM Reference > Here

DOM Element methods

Last updated: December 4th, 2006

Below lists the DOM methods that can be used on most elements in a document:

DOM Element methods

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.onload=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" onclick="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.
Sponsored By

DD CSS Library
Free CSS menus and codes to give your site a visual boost.

Daniweb JavaScript Community

DOM Window
DOM Document
DOM Element
DOM Event
DOM Style
DOM Table
Miscellaneous

 

CopyRight © 1998-2008 JavaScript Kit. NO PART may be reproduced without author's permission.