Testing for elements is good, but watch out for prototype.

So using css selectors is fairly easy in Prototype:

finding and element with ID:

$('name_of_id')

finding an element(s) with other selectors: (I am only using one example)

$$('.className')

Now before looking for an element, it’s always good to test whether it exists first.

So lets test for the element, and if it’s there… hide it.

if ( $('name_of_id') ) {
$('name_of_id').hide();
};

Important notice:

Keep in mind that using the prototype Utility methods $() and $$() automatically extends the DOM element it’s calling.
What does that mean?
It means that there are many prototype methods added to the DOM element.
so you can do this:

$('name_of_id').hide();

but try doing that here:

document.getElementByID('name_of_id').hide();

because the DOM element is not extended with prototype methods.

Testing for elements before using

So using the single dollar sign selector will look like this:

if ( $('name_of_id') ) {
$('name_of_id').hide();
};

However!
The above code is testing whether an object exists, but using the double dollar will fail.

Instead use this:

if ( $$('.className').length > 0 ) {
$$('.className').hide();
};

Why?  Because using the double dollar selector automatically creates an array.   Therefore, testing for $$(”) will always return true.  That’s bad.

This is why using the length property will return an array.  Even if there is no element in the DOM.

ie.  $$('.noClass') == []

This entry was posted in javascript / jQuery. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>