2

I'm developing a small library to learn more about javascript

I am using a chaining pattern:

(function(window) {
    var myLibrary = function(iD) {
        var e = document.getElementById(iD),
            methods = {
                one: function(val) {
                    e.innerHTML = val;
                    return this; // maintain chainability
                },
                two: function(val) {
                    alert(val);
                    return this; // maintain chainability
                }
            };
        return methods;
    };
    window.myLibrary = myLibrary;
})(window);

chaining is fine, but I can not use an internal property of JavaScript. for example

myLibrary("ID").length

any idea to return the item?

2
  • 2
    What exactly do you expect .length to represent? You're always retrieving one (or zero) element (by id)...so it wouldn't make sense to represent the number of elements found (like how jQuery does it). Commented Jul 23, 2013 at 5:37
  • 2
    I don't know if it helps, but here's more or less how I'd set up this "library": jsfiddle.net/mq38W/1 (I'd say it's somewhat close to how jQuery handles things, although there are obviously many things missing, as well as not being structured exactly the same) Commented Jul 23, 2013 at 5:52

1 Answer 1

2

length properties are generally associated with ordered collections like Strings and Arrays. methods, as an Object, is neither.

So, if you want it to have a length, you have to give it one:

methods = {
    length: e == null ? 0 : 1,

    // ...
};
myLibrary('ID').length

Or, define a method that returns something other than this that would have a length itself:

methods = {
    html: function () {
        return e.innerHTML;
    },

    // ...
};
myLibrary('ID').html().length
Sign up to request clarification or add additional context in comments.

4 Comments

i think she wants to get the number of elements with length which is always 1/0
@Ankit The 1st snippet demonstrates that, to the limits of getElementById() -- e == null ? 0 : 1.
+1yeah you are right however i am not liking the way on which this library is getting built
confused me, put documen.getElementById by document.getElmentsByTagName

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.