Below we have a bulk of span elements and we'd like to set the text colors without having to type in the id or CSS attributes. We would use the Document Object Model (DOM) object and collection method to access each element and set the style attributes for each element. The script below assigns an id, color and border attribute to each span element that's inside the blockquote element. The color attribute depends on the id of each span element.
The sample code below gives the XHTML and JavaScript code to handle this; the for loop sets the display, padding and border for rendering clarity but isn't necessary. There are 2 functions; doThis()1 and doThis2()2.
1Function doThis() has a match in the first position of the switch statement. This is to illustrate that execution begins here and continues through the remaining case matches; since there are no break or return statements.
2Function doThis2() has a match in the last position of the switch statement; showing that it is the only case match and so the only formatting that is applied.
Paste the code in your editor to see ...
HTML Code
<blockquote id="sampleBlock">
<span style="display:block">This is span 1</span>
<span style="display:block">This is span 2</span>
<span style="display:block">This is span 3</span>
<span style="display:block">This is span 4</span>
<span style="display:block">This is span 5</span>
</blockquote>
JavaScript Code
<script language="JavaScript" type="text/javascript">
function domElement(objID) {return document.getElementById(objID) ;} ;
function domCollection(domObj,tagName) {return domObj.getElementsByTagName(tagName)} ;
spans=domCollection(domElement("sampleBlock"),"span") ;
/* this for loop just simplifies rendering */
for (i=0 ; i < spans.length ; i++)
{
spans[i].id="span"+i;
spans[i].style.border="solid 1px lightgrey";
spans[i].style.padding="2px";
};
doThis=function()
{
switch (spans[0].id)
{
case "span0" :
domElement("span0").style.color="red" ;
case "span2" :
domElement("span2").style.color="cyan" ;
case "span3" :
domElement("span3").style.color="yellow" ;
case "span4" :
domElement("span4").style.color="blue" ;
}
}
doThis2=function ()
{
switch (spans[0].id)
{
case "span2" :
domElement("span2").style.color="cyan" ;
case "span3" :
domElement("span3").style.color="yellow" ;
case "span4" :
domElement("span4").style.color="blue" ;
case "span0" :
domElement("span0").style.color="red" ;
}
}
/* the function calls below are commented out; uncomment them one at a time to see how this example works */
//doThis() ;
//doThis2() ;
</script>