开发者

adding a js method

I have a js function that is named getID which is basically return document.getElementById(id)

I want to make another function, getTag that would return getElementsByTagName.

The part that I can't seem to manage is that I want to be able to call them like this:

getID('myid').getTag('input') => so this would return all the input elements inside the element with the id myid

Thanks!

ps: getTag would also have to work if it's called by it's own, but then it would just return document.getElementsByTagName

UPDATE:

Thanks to all that have replied! Using your suggestions I came up with this, which works well for me:

function getEl(){
    return new getElement();
}

function getElement() {
    var scope = document;

    this.by = function(data){
        if (data.id)    scope = scope.getElementById(data.id);
        if (data.tag)   开发者_StackOverflow中文版scope = scope.getElementsByTagName(data.tag);

        return scope;
    }
}

and I use it like this:

var inputs = getEl().by({id:"msg", tag:"input"});


The way to do that is to prototype Object. To do that, you'll need the following piece of code:

Object.prototype.getTag = function(tagName) {
    return this.getElementsByTagName(tagName);
}

However, this will expand all objects because what you really need to prototype, an HTMLElement, is very hard to do consistently. All the experts agree that you should never expand the Object prototype. A much better solution would be to create a function that gets the tag name from another argument:

function getTag(tagName, element) {
    return (element || document).getElementsByTagName(tagName);
}

// Usage
var oneTag = getTag('input', getID('myid')); // All inputs tags from within the myid element
var twoTag = getTag('input'); // All inputs on the page


This would require that whatever is returned by getID('myid') (an HTML element) exposes a method named getTag(). This is not the case. Browsers implement the DOM specification and expose the methods defined there.

While you technically can enhance native objects with your own methods, it's best not to do it.

What you try to do has been solved rather nicely in JS libraries like jQuery already, I recommend you look at one of them before you invest time in mimicking what they can do. For example, your line of code would become:

$("#myid input")

in jQuery. jQuery happens to be the most widely used JS library around, there are many others.


Basically, you're going to create a single object that contains each of your methods and also stores all data returned by the native functions. It would look something like this (not tested, but you get the idea):

var MyLib = {
    getID: function(id) {
        var element = document.getElementById(id);
        this.length = 1;
        this[0] = element;
        return this;
    },
    getTag: function(tag) {
        var elements;
        if (this.length) {
            for (var i = 0; i < this.length; i++) {
                var byTag = this[i].getElementsByTagName(tag);
                for (var j = 0; j < byTag.length; j++) {
                    elements.push(byTag[j]);
                }
            }
        }
        for (var i = 0; i < elements.length; i++) {
            this[i] = elements[i];
        }
        this.length = elements.length;
        return this;
    }
};

You can then use it like this:

var elements = MyLib.getID('myid').getTag('input');
for (var i = 0; i < elements.length; i++)
    console.log(elements[i]); // Do something

The only real problem with this approach (besides it being very tricky and hard to debug) is that you have to treat the result of every method like an array, even if there is only a single result. For example, to get an element by ID, you'd have to do MyLib.getID('myid')[0].

However, note that this has already been done before. I recommend you take a look at jQuery, if only to see how they accomplished this. Your code could be simplified to this:

$("#myid input")

jQuery is more lightweight than you think, and including it on your page will not slow it down. You have nothing to lose by using it.


Just use the DOMElement.prototype property.

You'll get something like this :

function getTag(tagName) {
    return document.getElementsByTagName(tagName);
}
DOMElement.prototype.getTag = function(tagName) {
    return this.getElementsByTagName(tagName);
}

But you should use jQuery for this.

EDIT: My solution doesn't work on IE, sorry !


You could define it as follows:

var Result = function(el)
{
  this.Element = el;
};

Result.prototype.getTag = function(tagName)
{
  return this.Element.getElementsByTagName(tagName);
};

var getTag = function(tagName)
{
  return document.getElementsByTagName(tagName);
};

var getID = function(id)
{
  var el = document.getElementById(id);
  return new Result(el);
};

Whereby a call to getID will return an instance of Result, you can then use its Element property to access the HTML element returned. The Result object has a method called getTag which will return all child elements matching that tag from the parent result. We then also define a seperate getTag method which calls the document element's getElementsByTagName.

Still though...JQuery is so much easier... $("#myId input");


Unless this is an academic exercise on how to chain methods in JavaScript (it doesn't seem to be, you simply seem to be learning JavaScript), all you have to do is this:

var elements = document.getElementById("someIdName");
var elementsByTag = elements.getElementsByTagName("someTagName");
for (i=0; i< elementsByTag.length; i++) {
    alert('found an element');
}

If you want to define a reusable function all you have to do is this:

function myFunction(idName,tagName) {
    var elements = document.getElementById(idName);
    var elementsByTag = elements.getElementsByTagName(tagName);
    for (i=0; i< elementsByTag.length; i++) {
        alert('found a ' + tagName + ' element within element of id ' + idName);
    }
}

It's true that if this is all the JavaScript functionality you need on your page, then there is no need to import jQuery.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜