2012-04-29

Javascript: Get a Element's {Type, Name, Value}

Perm URL with updates: http://xahlee.org/js/js_get_node_info.html

This page shows you how to get a HTML/XML element's {type, name, value}.

Node Type

Use ‹node›.nodeType to get a element's type. The ‹node› is a HTML element object.

The return value is a number. Usually 1 or 3. “1” means it's a HTML/XML element. “3” means its content.

Here's a complete list:

  • ELEMENT_NODE → 1
  • ATTRIBUTE_NODE → 2
  • TEXT_NODE → 3
  • CDATA_SECTION_NODE → 4
  • ENTITY_REFERENCE_NODE → 5
  • ENTITY_NODE → 6
  • PROCESSING_INSTRUCTION_NODE → 7
  • COMMENT_NODE → 8
  • DOCUMENT_NODE → 9
  • DOCUMENT_TYPE_NODE → 10
  • DOCUMENT_FRAGMENT_NODE → 11
  • NOTATION_NODE → 12

sample code:

var xx = document.getElementById("id63656");

alert("type is:" + xx.nodeType);

alert("firstChild type is:" + xx.firstChild.nodeType);

javascript test page: nodeType.

As of , this works in all major browsers.

Node Name

‹node›.nodeName returns the node's (tag) name (as string), if the node is a element node (nodeType returns 1). If it's a text node, the value is "#text". See references for all possible values for different types of node.

var xx = document.getElementById("id43160");

alert("name is:" + xx.nodeName);

alert("firstChild name is:" + xx.firstChild.nodeName);

javascript test page: nodeName

As of , this works in all major browsers.

Node Value

Use ‹node›.nodeValue to get the content of text node. For most other node types, it returns null.

var xx = document.getElementById("id82521");

alert("node value is:" + xx.nodeValue);

alert("firstChild node value is:" + xx.firstChild.nodeValue);

javascript test page: nodeValue

To change a html element's content, you can just set “nodeValue” to some text. See: Javascript: Changing HTML Content Example.

As of , this works in all major browsers.