Categories:

JavaScript Kit > DOM Reference > Here

DOM Element methods

Last updated: June 17th, 2009

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

DOM Element methods

Properties Description
addEventListener(eventType, listener, useCapture)

Not supported in IE, which uses attachEvent() instead.

Associates a function with a particular event and binds the event to the current node. 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 object or function to fire when the event fires. The actual parameter entered should be a reference to the function or object (ie: "dothis" instead of "dothis()".
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

Since listener must be a function reference, a common question is how to specify the listener so it can receive parameters of its own. The solution is just to wrap the listener in an anonymous function reference:

function dothis(what){
 alert("Mom says to do " + what)
}

if (window.addEventListener)
 window.addEventListener("load", function(){dothis('Your homework')}, false) //invoke function

For events such as "click" or "mousemove" that populate the Event object with additional info such as where the mouse is at the time, addEventListner() passes this object silently to the listener. To receive it, define a single parameter in the anonymous function:

function getcoord(evt){
 alert("You clicked at coordinates [" + evt.clientX + "," + evt.clientY + "]")
}

if (document.addEventListener)
 document.addEventListener("click", function(evt){getcoord(evt)}, false) //invoke function

attachEvent(eventType, function)

IE 5+only 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>

An interesting feature of appendChild() is that it can be used to directly move an existing element on the page so it becomes the child of a different parent. There's no need to remove the element from the previous parent first, as the method always checks to see first if the element beind appended currently already has a parent, and remove it from that parent first if found to be true. The below example moves a H1 element from its current location to the very end of the document:

<h1 id="myheader">Welcome to JavaScript Kit</h1>
<p>Hope you enjoy the site!</p>

<script type="text/javascript">
document.body.appendChild(document.getElementById("myheader")) //moves "myheader" to end of the page

</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 as if the user manually clicked on it. In most browsers, click() only works on form INPUT elements that's non "submit" or "reset". It can't be used to simulate a click on a link or form submit button.
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)

IE 5+only 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)

Not supported in IE, which uses fireEvent() instead.

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.
getElementsByClassName

Note: Supported in FF3+, Opera 9.5+, Safari 3+, though not IE8.

Gets a collection of element(s) within the invoking element that shares the designated CSS class name, for example:

//get elements within element "house" that has a CSS class of "cats"
document.getElementById("house").getElementsByClassName("cats")

You can get elements with different CSS class names within an element all in one scoop, by separating each class with a space:

//get elements within element "house" that has a CSS class of "cats" or "dogs"
document.getElementById("house").getElementsByClassName("cats dogs")

Note that getElementsByClassName() also exists on the document element to get every matching element within the document.

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) 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) 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.
querySelector(selectors, [NSResolver])

Note: Currently supported in FF3.1+, IE8+ (only in IE8 standards mode), and Safari 3.1+

Accepts a CSS selector(s) and returns the first matching element (based on the document tree) within the invoking element, or null.

Example:

<ul id="mylist">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<script type="text/javascript">
var item2=document.getElementById("mylist").querySelector('li:nth-of-type(2)')
alert(item2.innerHTML) //alerts "Item 2"
</script>

You can enter multiple CSS selectors each separated by a comma (,), in which case the first matching element of any of the CSS selectors entered will be returned:

//returns either element "#leftcolumn" or "#rightcolumn", depending on which one is found first:
myelement.querySelector("#leftcolumn, #rightcolumn")

querySelector() supports an optional 2nd "NSResolver" parameter to resolve namespace prefixes in XHTML documents. Not supported in IE8.

querySelectorAll(selectors, [NSResolver])

Note: Currently supported in FF3.1+, IE8+ (only in IE8 standards mode), and Safari 3.1+

Accepts a CSS selector(s) and returns all matching elements (based on the document tree) within the invoking element as a staticNodeList, or null. A staticNodeList is a static collection of elements that are not affected by any subsequent changes occuring on the document tree.

Example:

<ul id="mylist">
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

<script type="text/javascript">
var odditems=document.getElementById("mylist").querySelectorAll('li:nth-of-type(odd)')
for (var i=0; i<odditems.length; i++)
 alert(odditems[i].innerHTML) //alerts "Item 1", "Item 3" etc.
</script>

You can enter multiple CSS selectors each separated by a comma (,), in which case all matching elements found using the entered CSS selectors will be returned:

//returns both elements "#leftcolumn" or "#rightcolumn", or one of them if only one defined:
myelement.querySelectorAll("#leftcolumn, #rightcolumn")

querySelectorAll() supports an optional 2nd "NSResolver" parameter to resolve namespace prefixes in XHTML documents. Not supported in IE8.

See "Overview of CSS3 Structural puesdo-classes" for advanced CSS selectors you can use with the query selector methods.

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)

Not supported in IE, which uses detachEvent() instead.

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.

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

 

CopyRight (c) 2018 JavaScript Kit. NO PART may be reproduced without author's permission. Contact Info