Accessing Tags


document.getElementsByTagName("p") 

An alternative way to access elements on the current page is to access them through the tag names.

Whenever you have to work on a set of elements that are represented by the same HTML tags (for instance, all list items or all paragraphseverything that is not represented by another property of the JavaScript document object), the method document.getElementsByTagName() can be used. You provide the tag name and get an array of all elements, which you can then process further.

The following code just accesses all <p> elements and counts them:

Accessing Elements By Tag Name (getelementsbytagname.html)

<script language="JavaScript"   type="text/javascript"> window.onload = function() {   window.alert(     document.getElementsByTagName("p") +     " (" + document.getElementsByTagName("p").length     + " elements)"); } </script> <p>JavaScript Phrasebook</p> <p>Sams Publishing</p> 

The output of the preceding code is [object HTMLCollection] (2 elements); Internet Explorer once again gives less information, outputting [object] (2 elements).

Navigating the DOM Tree

After you are inside the DOM, you can navigate in the DOM structure, going both up and down, to the left and to the right. Here is a list of the most important properties every DOM node has:

  • firstChild: first child node

  • lastChild: last child node

  • childNodes: all child nodes (as an array)

  • parentNode: parent node

  • nextSibling: next node on the same level ("to the right")

  • previousSibling: previous node on the same level ("to the left")

Also, nodeName returns the name of the tag of the node (or #text for text nodes), whereas nodeValue returns the value of a node (useful with text nodes).





JavaScript Phrasebook(c) Essential Code and Commands
JavaScript Phrasebook
ISBN: 0672328801
EAN: 2147483647
Year: 2006
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net