Categories:

Creating custom collections out of "class" elements on the page

So far we've hidden certain content on our page by dynamically generating the appropriate stylesheet and applying it to content via the "class" attribute of CSS:

<script type="text/javascript">
if (document.all || document.getElementById){ //if IE4 or NS6+
document.write('<style type="text/css">')
document.write('.dyncontent{display:none;}')
document.write('</style>')
}
</script>

<p class="dyncontent">This content is hidden from view initially</p>
<p class="dyncontent">This content is hidden from view initially as well</p>
<p >This content is not hidden from view.</p>

So the real question now becomes, how do we get to those content in our script? Ah by worshipping the DOM (Document Object Model) of modern browsers of course!

The DOM allows us to theoretically assess any element on the page and manipulate it. Now, you may be familiar with methods like document.getElementById or document.getElementsByTagName, which allow you to access an element based on these two criteria. However, and no, your memory's fine, there's currently no pre-build method to retrieve an element by ClassName (as of IE6/NS7), the way we've chosen to identify our content above. All is not lost, however. We can still do it in a roundabout way:

<script type="text/javascript">
function getElementbyClass(classname){
var inc=0
var alltags=document.all? document.all : document.getElementsByTagName("*")
for (i=0; i<alltags.length; i++){
if (alltags[i].className==classname)
customcollection[inc++]=alltags[i]
}
}

getElementbyClass("dyncontent")
</script>

The key here is the line:

var alltags=document.all? document.all: document.getElementsByTagName("*")

We rely on document.getElementsByTagName("*") to first retrieve all elements on the page (the * denotes "everything"), then scan through each element to see if it carries the className we're interested in. If so, it's added to our custom collection. Notice how document.all is also used if it's supported- this is for sake of IE4 that do not recognize document.getElementById, yet with document.all can mimic what's required to get the job done.

A big hurdle cleared. With our custom collection in place, what to do with regular HTML content on your page becomes a matter of the imagination. Lets create a slideshow out of it!