spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / javascript / domscripting / 1 To page 1To page 2current pageTo page 4To page 5To page 6To page 7
[previous][next]
Biz Resources
Data Integration Software
Web Hosting
Email Solutions
Developer News
MicrosoftÂ’s Automated Agent: Can We Talk?
Borland Finally Sells CodeGear
Red Hat Heads For The JON 2.0

Scripting for 5th Generation Browsers and Beyond

Retrieving Elements

The two most common methods of retrieving elements based on the W3C DOM are the document.getElementById() and document.getElementsByTagName() methods. Both of these methods are important to learn as they form the basis of much of what follows.

The document.getElementById() method as the name implies retrieves an element by passing the id as an argument. For example:

<div id="eddieLayer" 
     style="position:absolute; width:200px; height:115px; 
     z-index:1; left: 40px; top: 80px; visibility: visible">
This is a CSS Layer with an id of eddieLayer
</div>

would be retrieved with JavaScript by using

theDiv = document.getElementById('eddieLayer').style

We can then utilize the variable theDiv to dynamically manipulate the style attributes of the <div> tag as indicated below: (live example)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Manipulating a Div Element</title>
<script language="JavaScript" type="text/javascript">
function moveDiv() { 
	theDiv = document.getElementById('eddieLayer').style;
	theDiv.left = 400;
}
</script>
</head>
<body bgcolor="#FFFFFF">
<a href="#" onMouseDown="moveDiv()"> Let's move the div </a>
<div id="eddieLayer" 
     style="position:absolute; width:200px; height:115px; 
     z-index:1; left: 40px; top: 80px; visibility: visible">
This is a CSS Layer with an id of eddieLayer
</div>
</body>
</html>

We can also refine the moveDiv() function to a single line of script as such:

function moveDiv() { 
	 document.getElementById('eddieLayer').style.left=400;
}

However, it is often more useful to define a variable for later use, because that variable can be used repeatedly. For example,

theDiv.left = 400;
theDiv.top = 500;
theDiv.visibility = hidden;
theDiv.width = 350;

By using the document.getElementById() method and adding the style attributes as in document.getElementById('eddieLayer').style every CSS attribute of that layer becomes exposed to dynamic manipulation. In short, it provides Web developers with a range of options when working with Dynamic HTML Web pages which goes beyond just manipulating a CSS layer.

For instance, let us suppose we wanted to directly manipulate an image element that is not in a CSS layer, we could use exactly the same methods as above, but with the provision that we assign a unique id to the image and add the style="position:absolute; attribute as the next example shows. (live example)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Manipulating a Image</title>
<script language="JavaScript" type="text/javascript">
function moveImage() { 
	theImg = document.getElementById('dolphin').style;
	theImg.left = 400;
}
</script>
</head>
<body bgcolor="#FFFFFF">
<p><a href="#" onMouseDown="moveImage()"> Let's move the image </a></p>
<p><img src="dolphin.jpg" id="dolphin" 
        style="position:absolute;  width="480" height="360"> </p>
</body>
</html>

I can almost see the light switching on in peoples' heads as they begin to realize the inherent potential of this method. The restriction of the document.getElementById() method is that it can only be used to access individual elements that have a unique id attribute.

A way to overcome this limitation is the document.getElementsByTagName() collection. This method takes the tag type as its argument and returns all of the tags of that particular type in an HTML document. In essence it is a collection method as in returning an array. For example,

theImg= document.getElementsByTagName("img");

returns all the images in a document regardless of whether they have a name or id attribute. The following example returns an alert that displays the number of images in the document as a way of demonstrating how elements are collected by using the document.getElementsByTagName() method. (live example)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Retrieving How Many Images In a Document</title>
<script language="JavaScript" type="text/javascript">
function getImages(){
theImg= document.getElementsByTagName("img");
alert(theImg.length)
}
</script>
</head>
<body bgcolor="#FFFFFF">
<p><a href="#" onMouseDown="getImages()"> How many 
    images in this document? </a></p>
<p><img src="dolphin.jpg" width="480" height="360"> </p>
<p><img src="dolphin.jpg" width="480" height="360"> </p>
<p><img src="dolphin.jpg" width="480" height="360"> </p>
</body>
</html>

We can also traverse the DOM tree and target specific page elements. For example, let's assume that we wanted to obtain the height of the first CSS layer in a document, then something along these lines could be employed:

getHeight = document.getElementsByTagName('div')[0].offsetHeight;

The [0] in the above line of script is an array index. In JavaScript the 0 value represents the first element in an array. Consequently, the above line of script would target the first CSS layer in the document and return its height value. The distinction to make here is that the document.getElementById() method retrieves elements which have a unique id, where as the document.getElementsByTagName() method could be used to either target individual elements that do not have a unique id assigned to them or retrieve a collection of the same tag.

Please note that the offsetHeight and offsetWidth properties are supported by both IE5+ and NS6 even though they are not a W3C recommendation.

Contents:

home / programming / javascript / domscripting / 1 To page 1To page 2current pageTo page 4To page 5To page 6To page 7
[previous][next]

Access FREE Mainsoft Tools:
Whitepaper:
Integrate SharePoint into WebSphere Portal
Demo:
Integrate SharePoint and .NET into WebSphere Portal
Tutorial: Integrate SharePoint Data into WebSphere Portal & Build a Composite Application Across SharePoint, .NET, & Java Tutorial:
Create WebSphere Portal Applications using the Visual Studio IDE



JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Microsoft Article: HyperV-The Killer Feature in WinServer ‘08
Avaya Article: How to Feed Data into the Avaya Event Processor
Microsoft Article: Install What You Need with Win Server ‘08
HP eBook: Putting the Green into IT
Whitepaper: HP Integrated Citrix XenServer for HP ProLiant Servers
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 1
Intel Go Parallel Portal: Interview with C++ Guru Herb Sutter, Part 2--The Future of Concurrency
Avaya Article: Setting Up a SIP A/S Development Environment
IBM Article: How Cool Is Your Data Center?
Microsoft Article: Managing Virtual Machines with Microsoft System Center
HP eBook: Storage Networking , Part 1
Microsoft Article: Solving Data Center Complexity with Microsoft System Center Configuration Manager 2007
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Video: Are Multi-core Processors Here to Stay?
On-Demand Webcast: Five Virtualization Trends to Watch
HP Video: Page Cost Calculator
Intel Video: APIs for Parallel Programming
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
Microsoft Silverlight Video: Creating Fading Controls with Expression Design and Expression Blend 2
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
Sun Download: Solaris 8 Migration Assistant
Sybase Download: SQL Anywhere Developer Edition
Red Gate Download: SQL Backup Pro and free DBA Best Practices eBook
Red Gate Download: SQL Compare Pro 6
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
How-to-Article: Preparing for Hyper-Threading Technology and Dual Core Technology
eTouch PDF: Conquering the Tyranny of E-Mail and Word Processors
IBM Article: Collaborating in the High-Performance Workplace
HP Demo: StorageWorks EVA4400
Intel Featured Algorhythm: Intel Threading Building Blocks--The Pipeline Class
Microsoft How-to Article: Get Going with Silverlight and Windows Live
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES
webref The latest from WebReference.com Browse >
Perl Pragma Primer · Implement Drag and Drop in Your Web Apps: Part 2 · How to Create an Ajax Autocomplete Text Field: Part 5
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
SQL Server 2005 Express Edition - Part 22 - Upgrading from Microsoft SQL Server Desktop Engine (MSDE) · Vyatta: Downgrades that Pay Off · NetMotion Brings Cross-Network Support to Wireless VoIP


Created: August 16, 2001
Revised: August 16, 2001


URL: http://webreference.com/programming/javascript/domscripting/1/3.html