MathCurvesSurfacesWallpaper GroupsGallerySoftwarePOV-Ray
ProgramingLinuxPerl PythonHTMLCSSJavaScriptPHPJavaLang DesignEmacsUnicode ♥

JavaScript: Most Frequently Used DOM Methods

,

This page shows Common DOM methods.

Getting Elements in a Document

document.getElementById(‹id›). The ‹id› should be a string.

document.getElementsByTagName(‹tagname›) Returns a array. The ‹tagname› are {div, span, p, a, img, …}, and they should be string.

document.getElementsByClassName(‹class value›) Returns a array. The ‹class value› should be a string.

Example: JavaScript: Get Elements by ID, Tag, Name, Class.

Get and Set Element Attribute's Value

‹node›.getAttribute(‹attribute›) Get a element's attribute (⁖ {id, href, title, style})'s value.

‹node›.setAttribute(‹attribute›, ‹value›) Sets the value of the attribute with the name attribute to value

Example: Get AttributeSet Attribute.

Get Node Type, Name, Value

‹node›.nodeType Return the type of the node (1 → element, 3 → text node)

‹node›.nodeName Return the name of the node (either tag name or #text)

‹node›.nodeValue Return the value of the node (usually the text content of a HTML element)

Example: JavaScript: Get a Element's {Type, Name, Value}.

Navigating Between Nodes

‹node›.previousSibling Return the previous sibling of ‹node›, or null if it doesn't exist.

‹node›.nextSibling Return the next sibling of ‹node›, or null if it doesn't exist.

‹node›.childNodes Return all children of ‹node› as a list.

‹node›.firstChild Return the first child of ‹node›.

‹node›.lastChild Return the last child of ‹node›.

‹node›.parentNode Return the parent of ‹node›.

Example: previousSibling nextSibling childNodes firstChild lastChild parentNode

Creating New Nodes

document.createElement(element) Creates a new element node with the name element. You provide the name as a string.

document.createTextNode(string) Creates a new text node with the node value of string.

‹node›.cloneNode(‹with children›) Returns a copy of ‹node›. If ‹with children› is true, the returned node includes all child nodes.

‹node›.appendChild(‹new node›) Adds ‹new node› as a the last child to ‹node›.

‹node›.insertBefore(‹node 1›, ‹node 2›) Inserts ‹node 1› as a new child of ‹node› before ‹node 2›.

‹node›.removeChild(oldNode) Removes the child oldNode from node.

‹node›.replaceChild(newNode, oldNode) Replaces the child node oldNode of node with newNode.

element.innerHTML Reads or writes the HTML content of the given element as a string—including all child nodes with their attributes and text content.

Content of this page is based on Christian Heilmann's work. It is licensed under Creative Commons Attribution (©cc).

blog comments powered by Disqus