04.11.2015 Views

javascript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

The Element Type<br />

Chapter 10: The Document Object Model<br />

Next to the Document type, the Element type is most often used in web programming. The Element<br />

type represents an XML or HTML element, providing access to information such as its tag name,<br />

children, and attributes. An Element node has the following characteristics:<br />

❑<br />

❑<br />

❑<br />

❑<br />

❑<br />

nodeType is 1.<br />

nodeName is the element ’ s tag name.<br />

nodeValue is null .<br />

parentNode may be a Document or Element .<br />

Child nodes may be Element , Text , Comment , ProcessingInstruction , CDATASection , or<br />

EntityReference .<br />

An element ’ s tag name is accessed via the nodeName property or by using the tagName property; both<br />

properties return the same value (the latter is typically used for clarity). Consider the following element:<br />

< div id=”myDiv” > < /div ><br />

This element can be retrieved and its tag name accessed in the following way:<br />

var div = document.getElementById(“myDiv”);<br />

alert(div.tagName); //”DIV”<br />

alert(div.tagName == div.nodeName); //true<br />

The element in question has a tag name of div and an ID of “ myDiv ” . Note, however, that div.tagName<br />

actually outputs “ DIV ” instead of “ div ” . When used with HTML, the tag name is always represented in<br />

all uppercase; when used with XML (including XHTML), the tag name always matches the case of the<br />

source code. If you aren ’ t sure whether your script will be on an HTML or XML document, it ’ s best to<br />

convert tag names to a common case before comparison, as this example shows:<br />

if (element.tagName == “div”){ //AVOID! Error prone!<br />

//do something here<br />

}<br />

if (element.tagName.toLowerCase() == “div”){ //Preferred - works in all documents<br />

//do something here<br />

}<br />

This example shows two comparisons against a tagName property. The first is quite error - prone because<br />

it won ’ t work in HTML documents. The second approach, converting the tag name to all lowercase, is<br />

preferred because it will work for both HTML and XML documents.<br />

The Element type constructor and prototype are accessible in script in all browsers, including<br />

IE as of version 8.<br />

279

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!