JavaScript prototyping tutorial

I have a JS script with many functions, for large values:

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

      

It just saves me a lot of bytes when typing document.getElementById () every time. My problem is that I often add and remove classes and other attributes from elements. I want to be able to do this:

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

      

Does anyone know of any good Javascript prototypes that can explain this? Thank.

+2


source to share


4 answers


the method you are looking for is the chaining method. basically, the "id" function should return an instance of an object that has an "addClass" method on it. and this method will "return this".

Here is a tutorial explaining this concept:
http://javascriptant.com/articles/32/chaining-your-javascript-methods



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

+1


source


I have to ask: Do you think you are using something like jQuery? If you've been doing this problem, it's simple:

$("#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 the element has 3 classes, the actual attribute is fair:



"one two three"

      

Another aspect, of course, is writing an extension method.

+4


source


You cannot achieve this for all browsers, in particular, it is not possible to extend the methods available on an element in IE6 or 7.

To be honest, you would save bags of time if you included JQuery in your development.

+1


source


It's best to go with a framework if you can, for example says cletus.

However AnthonyWJones is not entirely correct - it is not possible to extend the methods available on the generic Element object, but you can add it to individual elements.

The id function can extend the returned elements using the 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 can even add it to the Element object (which automatically adds it to all elements on the page) for browsers that support this feature, and then only add the method to your id function for IE - this will save a little memory and speed, especially when you start adding many methods of Elements.

This behavior is exactly the same as MooTools solves this problem - it is repeated that it is better to use a framework where possible!

0


source







All Articles