views:

151

answers:

4

I have a JS script with tons of functions, on big on is this:

function id(i) {
    if(document.getElementById)
        return document.getElementById(i);
    return;
}

It just saves me many bytes in typing out document.getElementById() each time. My problem is I frequently add and remove classes and other attributes from elements. I want to be able to do this:

id('main').addClass("someClass");

Does anyone know any good Javascript Prototyping tutorials which can explain this? Thanks.

+3  A: 

I have to ask: have you considered just using something like jQuery? If you did the problem simply becomes:

$("#main").addClass("someClass");

and you're done. If the goal is to implement this yourself (if so, why?) then you just need to know that if an element has 3 classes, the actual attribute is just:

"one two three"

The other aspect of course is writing an extension method.

cletus
A: 

the technique you're looking for is method chaining. basically, the "id" function should return an object instance that has the "addClass" method on it. and that method would "return this".

Here's a tutorial that explains this concept:
http://javascriptant.com/articles/32/chaining-your-javascript-methods

I would also highly recommend this book to learn more techniques such as this (yes chaining is covered) :-)
http://jsdesignpatterns.com/

Joel Martinez
Method chaining would require that the existing id function in the question would have to be modified to return some other wrapper object.
AnthonyWJones
+1  A: 

You can't achieve that for all browsers, in particular its not possible to extend the methods available on an Element in IE6 or 7.

To be honest you would save yourself bags of time if you just include JQuery in your development.

AnthonyWJones
A: 

Best to go with a framework if you can, like cletus says.

However, AnthonyWJones isn't quite right - it isn't possible to extend the methods available on the generic Element object, but you can still add it to individual elements.

Your id function could extend returned Elements with an addClass method:

function get(id){
    el = document.getElementById(id);
    el.addClass = function(cls){
        // your addClass code here
        // (remember IE uses className, others use class)
    };
    return el;
}

You could even add it to the Element object (which automatically adds it to all the elements on the page) for browsers that support this feature and then only add method in your id function for IE - this will save on memory and speed up the application a bit, particularly when you start adding a lot of Element methods.

This behaviour is exactly how MooTools solves this problem - it bears repeating that it's better to use a framework where possible!

adamnfish