Javascript
length Property
Value: integer
Compatibility: WinIE3+, MacIE3+, Moz1+, Sasfari1+
The length property returns the number of items in an array or collection of objects. While arrays and collections use integer values as index values (starting with zero), the length value is the actual number of items in the group.
for(var i = 0; i < myArray.length; i++)
{
...
}
All browsers: document.forms.length
All browsers: document.forms[0].elements.length
Moz, IE4+: document.images.length
Moz: document.layers.length
IE4+: document.all.length
IE5+, W3C: document.getElementById(”myID”).childNodes.length
Related items: area, select and Array objects.
innerHTML and innerText Properties
Value: String
Compatibility: WinIE4+, MacIE4+, Moz1+, Safari1+
The innerHTML property contains not only the text content for an element , but also every bit of HTML tagging that is associated with that content. The browser interprets any HTML tags that you include in a string you assign to an element’s innerHTML property as tags. This also means that you can introduce entirely new nested elements.
The innerText property knows only about the text content of an element container, if you assign a string to the innerText property of an element and that string contains HTML tags , the tags and their angle brackets appear in the rendered page and are interpreted as live tags.
Do not modify the innerHTML property to adjust the HTML for frameset, html, head and title objects.
Code:
<html>
<head>
<title>innerHTML and innerText properties</title>
<style type="text/css">
h1 {font-size:18pt;font-weight:bold;font-family:Comic Sans MS,Arial sans-serif}
.small {font-size:12pt;font-weight:400;color:gray}
</style>
<script type="text/javascript">
function setText(form)
{
var content = form.textInput.value;
if(content)
{
document.getElementById("label").innerText = content;
}
}
function setHTML(form)
{
var content = form.HTMLInput.value;
if(content)
{
document.getElementById("label").innerHTML = content;
}
}
</script>
</head>
<body>
<form>
<p>
<input type="text" name="HTMLInput"
value="<I>First</I> Article <span class='small'>(of ten)</span>" size="50" />
<input type="button" value="Change HTML" onclick="setHTML(this.form)"/>
</p>
<p>
<input type="text" name="textInput"
value="<I>First</I> Article <span class='small'>(of ten)</span>" size="50" />
<input type="button" value="Change Text" onclick="setText(this.form)"/>
</p>
</form>
<h1 id="label">Article 1</h1>
<p>Add these eight nutritional powerhouses to your diet to help you look and feel youthful.</p>
</body>
</html>
Related items: outerHTML, outerText properties, replaceNode( ) method.
firstChild - lastChild Properties
Value: Node object reference
Compatibility: winIE5+, macIE5+, moz1+, safari1+
W3C DOM-based document object models are built around an architecture known as a node map. Each object defined by HTML is a node in the map. A node has relationships with other nodes in the document. A child node is an element that is contained by another element. The container is the parent of such a child. A parent object have zero or more children.
var nodeArray = document.getElementById(”elementID”).childNodes;
While you can use this array to get a reference to the first or last child node, the firstChild and lastChild properties offers shortcuts to those positions.
Code:
<html>
<head>
<title>firstChild - lastChild properties</title>
<script type="text/javascript">
function makeNewLi(txt)
{
var newItem = document.createElement("li");
newItem.innerHTML = txt;
return newItem;
}
function prepend(form)
{
var newItem = makeNewLi(form.input.value);
var firstLi = document.getElementById("mylist").firstChild;
document.getElementById("mylist").insertBefore(newItem, firstLi);
}
function append(form)
{
var newItem = makeNewLi(form.input.value);
var lastLi = document.getElementById("mylist").lastChild;
document.getElementById("mylist").appendChild(newItem);
}
function replaceFirst(form)
{
var newItem = makeNewLi(form.input.value);
var firstLi = document.getElementById("mylist").firstChild;
document.getElementById("mylist").replaceChild(newItem, firstLi);
}
function replaceLast(form)
{
var newItem = makeNewLi(form.input.value);
var lastLi = document.getElementById("mylist").lastChild;
document.getElementById("mylist").replaceChild(newItem, lastLi);
}
</script>
</head>
<body>
<h1>firstChild and lastChild properties</h1>
<hr />
<form>
<input type="text" name="input" /><br />
<input type="button" value="Insert at top" onClick="prepend(this.form)" />
<input type="button" value="Insert at bottom" onClick="append(this.form)" />
<input type="button" value="Replace at top" onClick="replaceFirst(this.form)" />
<input type="button" value="Replace at bottom" onClick="replaceLast(this.form)" />
</form>
<ol id="mylist">
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
<li>item 4</li>
</ol>
</body>
</html>
Related items: nextSibling, parentElement, parentNode, previousSibling properties, appendChild( ), hasChildNodes( ), removeChild( ), removeNode( ), replaceChild( ), replaceNode( ) methods.
currentStyle Property
Value: style object
Compatibility: WinIE5+, MacIE5+
Every element has style atrributes applied to it even if those atrributes are the browser’s default settings. Because an element’s style object reflects only those properties whose corresponding atrributes are set via CSS statements , you can not use the style property of an element object to view default style settings applied to an element.That’s where the currentStyle property comes in.
This property returns a read-only style object that contains values for every possible style property applicable to the element.
Related items: runtimeStyle, window.getComputedStyle( )
contentEditable Property
Value: Boolean
Compatibility: WinIE5.5+
Element tags can include a contentEditable attribute , whose value is echoed via the contentEditable property of the element. The default value for this property is inherit , which means that the property inherits whatever setting this property has in the hierarchy of HTML containers outward to the body. If you set the contentEditable property to true that element and all nested elements set to inherit the value become editable, conversely a setting of false turns off the option to edit the content.
Code:
<html>
<head>
<title>contentEditable property</title>
<style type="text/css">
.normal{color:black;}
.editing{color:red}
</style>
<script type="text/javascript">
function toogleEdit()
{
var newState = !editableText.isContentEditable;
editableText.contentEditable = newState;
editableText.className = (newState) ? "editing" : "normal";
editBtn.innerText = (newState) ? "Disable Editing" :"Enable Editing";
}
</script>
</head>
<body>
<h1>Editing Contents</h1>
<hr />
<p>Turn on editing to modify the follolwing text:</p>
<div id="editableText">
Edit this text on the fly...
</div>
<p>
<button id="editBtn" onclick="toogleEdit()" onfocus="this.blur()">Enable Editing</button>
</p>
</body>
</html>
Related items: isContentEditable property
clientWidth and clientHeight Properties
Value: integer
Compatibility: WinIE4+, MacIE4+, NN7, Moz1+, Safari1+
These two properties by and large reveal the pixel height and width of the content within an element whose stylesheet rule includes height and width settings. In theory , these measures do not take into account any margins, borders or padding that you add to an element by way of stylesheets. In practice different combinations of borders , margins and padding influence these values in unexpected ways.
For the document.body object the clientwidth and clientheight properties return the inside width and height of the window or frame.
Code:
<html>
<head>
<title>clientWidth and clientHeight properties</title>
<script type="text/javascript">
function displayLogo()
{
var pWidth = document.getElementById("mydiv").clientWidth;
var pHeight = document.getElementById("mydiv").clientHeight;
//correct for Windows/Mac discrepancies
var pTop = (document.getElementById("mydiv").clientTop) ?
document.getElementById("mydiv").clientTop :
document.getElementById("mydiv").offsetTop;
var logoWidth = document.getElementById("logo").style.pixelWidth;
//center logo horizontally against paragraph
document.getElementById("logo").style.pixelLeft = (pWidth - logoWidth) / 2;
//position image immediately below end of paragraph
document.getElementById("logo").style.pixelTop = pTop + pHeight;
document.getElementById("logo").style.visibility = "visible";
}
</script>
</head>
<body>
<button onClick="displayLogo()">Position and show logo art</button>
<div id="logo" style="position:absolute;width:120px;visibility:hidden">
<img src="logo.gif" />
</div>
<div id="mydiv" style="width:200px;">
<p>From the valley of the shadows
Into the darkness beyond
Feel the calling of pleasures
Overshadow man's emptiness
My guiltiness bleeds internally
Inside tunnels of blocked emotions
The silent screams within my inner being
Bursting forth in desperation</p>
</div>
</body>
</html>
To assist in the vertical positioning of the logo, the offsetTop property of the div object provides the position of the start of the div with respect to its outer container (body).
The className Property
A class name is an identifier that is assigned to the class attribute of an element. To associate a CSS rule with several elements in a document assing the same identifier to the class attributes of those elements, and use that identifier as the CSS rule’s selector. An element’s className property enables the application of different CSS rules to that element under script control.
Code:
<html>
<head>
<title>The className property</title>
<style type="text/css">
.newstyle{font-size:16pt;color:red}
</style>
<script type="text/javascript">
function toggleStyle(ID)
{
var elem = (document.all) ? document.all(ID) : document.getElementById(ID);
if(elem.className == "")
{
elem.className = "newstyle";
}
else
{
elem.className = "";
}
}
</script>
</head>
<body>
<form>
<input type="button" value="toogle" onClick="toggleStyle('article1')" />
</form>
<h1>Article 1</h1>
<p id="article1">Greece Hellas, officially known as the "Hellenic Republic" is the southeastern most country in Europe, occupying the southernmost part of the Balkan Peninsula.
It is bordered by Albania, X-Yugoslavia (the Republic of Skopje) and Bulgaria from the north, and the European part of Turkey from the northeast.
From the east by the Aegean Sea, from the south by the Mediterranean Sea, and from the west the Ionian Sea, including more than 400 islands,
which occupy more than one fifth of its total land territory the total area of the country is 131,957 square kilometers (50,949 square miles).</p>
<h1>Article 2</h1>
<p>The mainland portion of Greece comprises the regions of Thraki and Macedonia in the north;
Epirus, Thessaly, and Central Greece in the central section; and in the south Peloponnisos, a peninsula which is connected to the rest of the mainland by the Isthmus of Corinth.
The remainder of Greece consists of more than 400 islands, (only 149 are inhabited.)
These are Evia, Crete, or Kriti, the Northern Sporades, the Cyclades, the Dodecanisa, Chios, Limnos,
Lesvos, Samos, Samothraki, and Thassos, all of which are spread out in the Aegean Sea. In the west,
the Ionian Sea, is where the Eptanisa are found, a group of seven inhabited major islands and three small uninhabited ones.</p>
</body>
</html>
Save this code as class_name.html
Collecting Child Nodes
The childNodes property consists of an array of node objects contained by the current object.Note that child nodes consistof both elements objects and text nodes.Therefore ,depending on the containt of the current object, the number of childNodes and children collections may differ.
Caution: if you use the childNodes array in a for loop that iterates through a sequence of HTML or XML elements, watch out for the possibility that the browser treats source code whitespace as text nodes.
The code below contains an example of how you might code a function that “walks” the child nodes of a given node.
Code:
function walkChildNodes(objRef, n)
{
var obj;
if(objRef)
{
if(typeof objRef == "string")
{
obj = document.getElementById(objRef);
}
else
{
obj = objRef;
}
}
else
{
obj = (document.body.parentElement) ? document.body.parentElement : document.body.parentNode;
}
var output = ""; var indent = ""; var i, group, txt;
if(n)
{
for(i=0;i<n;i++)
{
indent += "+---";
}
}
else
{
n = 0;
output += "Child Nodes of " + obj.tagName;
output += "\n================\n";
}
group = obj.childNodes;
for(i=0;i<group.length;i++)
{
output += indent;
switch(group[i].nodeType)
{
case 1:
output += group[i].tagName;
output += (group[i].id) ? " ID=" + group[i].id : "";
output += (group[i].name) ? " NAME=" + group[i].name : "";
output += "\n";
break;
case 3:
txt = group[i].nodeValue.substr(0,15);
output += "[Text:" + txt.replace(/[\r\n]/g, "<cr>");
if(group[i].nodeValue.length > 15)
{
output += "...";
}
output += "]\n";
break;
case 8:
output += "[!COMMENT!]\n";
break;
default:
output += "[Node Type:" + group[i].nodeType + "]\n";
break;
}
if(group[i].childNodes.length > 0)
{
output += walkChildNodes(group[i], n+1);
}
}
return output;
}
Related items: nodeName, nodeType, nodeValue, parentNode properties.
cloneNode( ), hasChildNodes( ), removeNode( ), replaceNode( ), swapNode( ) methods.
Controlling the accessKey Property
For many elements ,you can specify a keybord character that, when typed as an Alt+key combination (windows) or Ctrl+key (mac) brings focus to that element.
The example below shows how to use the accessKey property to manipulate the keyboard interface for navigating a web page.When you load the script abjust the height of the browser window so that you can see nothing below the second dividing rule.Enter any character into the settings portion of the page and press Enter.Then hold down the Alt (windows) or Ctrl (mac) key while pressing the same keybord key.
Code:
<html>
<head>
<title>accessKey Property</title>
<script type="text/javascript">
function assignKey(type, elem)
{
if(window.event.keyCode == 13)
{
switch(type)
{
case "button":
document.forms["output"].access1.accessKey = elem.value;
break;
case "text":
document.forms["output"].access2.accessKey = elem.value;
break;
case "table":
document.getElementById("myTable").accessKey = elem.value;
}
return false;
}
}
</script>
</head>
<body>
<h1>
accessKey property lab</h1>
<hr />
Settings:<br />
<form name="input">
Assign an accessKey value to the button below and press return:
<input type="text" size="2" maxlength="1" onkeypress="assignKey('button', this)" /><br />
Assign an accessKey value to the text box below and press return:
<input type="text" size="2" maxlength="1" onkeypress="assignKey('text', this)" /><br />
Assign an accessKey value to the table below (IE5.5+) and press return:
<input type="text" size="2" maxlength="1" onkeypress="assignKey('table', this)" /><br />
</form>
<br />
Then press Alt (windows) or control (mac) + the key.<br />
<i>Size the browser window to view nothing lower than this line.</i>
<form name="output" onsubmit="return false">
<input type="button" name="access1" value="Standar Button" />
<input type="text" name="access2" />
</form>
<table>
<tr>
<th>Quantity</th>
<th>Description</th>
<th>Price</th>
</tr>
<tr>
<tbody bgcolor="red">
<td width="100">4</td>
<td>primary widget</td>
<td>15</td>
</tr>
<tr>
<td>10</td>
<td>secondary widget</td>
<td>100</td>
</tr>
</tbody>
</table>
</body>
</html>
Adding-Replacing DOM Content
You can perform text changes either via the replaceChild( ) method or by assigning new text to a text node’s nodeValue property.The second way is a simpler approach for replacing text nodes.All it requires is a reference to the text node being replaced. You can assign that node’s nodeValue property its new string value:
document.getElementById(”parag2″).childNodes[0].nodeValue = “first”;
Code:
<html>
<head>
<title>Adding-replacing dom content</title>
<script type="text/javascript">
function modify()
{
var newElem = document.createElement("p");
newElem.id = "newP";
var newText = document.createTextNode("This is the second paragraph.");
newElem.appendChild(newText);
document.body.appendChild(newElem);
document.getElementById("parag2").childNodes[0].nodeValue = "first";
}
</script>
</head>
<body>
<button onclick="modify()">Add-Replace text</button>
<p id="parag1">This is the <span id="parag2">one</span> paragraph on the page.</p> </body> </html>
When an element’s content is entirely text this is the most streamlined way to swap text on the fly using the W3C DOM syntax.
