Make alias to document.getElementById in Javascrip

2020-02-05 07:38发布

How can I alias the function "document.getElementById" I've seen it done using $

Thanks

7条回答
甜甜的少女心
2楼-- · 2020-02-05 08:02

Here's something I use in my own library. DOM is the class and $ is a function which is a shortcut implementation of the getElementById function:

function DOM()
{
  this.$ = function(elementIDs)
  {
    var el;

    // If an array of element names is passed.
    if (arguments.length > 1) 
    {
      var elements = [];
      var length = arguments.length;
      for (var i = 0; i < length; i++)
      {
        // Call this function recursively for each passed parameter.
        elements.push(this.$(arguments[i]));
      }
      return elements;
    }

    // If a single element name is passed.
    if (typeof(elementIDs) == "string")
    {
      el = document.getElementById(elementIDs);
    }
    return el;
  }
}

Usage:

var el = new DOM().$("elementID");

You can alias it to the top level window element.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2020-02-05 08:03

Possibly the easiest/shortest way:

function $(id) { return document.getElementById(id); };
查看更多
三岁会撩人
4楼-- · 2020-02-05 08:05

facebook's connect-js does the following in src/core/prelude.js:

if (!window.FB) {
  FB = {
    // ...
    $: function(id) {
      return document.getElementById(id);
    }
    // ...
  }
}

Then, to use it, they do:

FB.$('name-of-id');

The initial block creates the global object FB. They use this object, FB, as a namespace and define all their objects, properties, and functions within it. That way, it will work with other JavaScript code as long as that other code doesn't use the global object FB.

查看更多
一夜七次
5楼-- · 2020-02-05 08:06

When you've seen the $() function, it was probably some library such as jQuery or Prototype. The $ function is not an alias for document.getElementById, but is a wrapper that extends the functionality of the function.

To create your own wrapper, you could write a function "alias":

var alias = document.getElemenyById;

or

function alias(id) { return document.getElementById(id); }

But really, I would use one of the libraries available such as jQuery or Prototype.

查看更多
虎瘦雄心在
6楼-- · 2020-02-05 08:10

The new features introduced in ES6 let us improve on Chris Lloyd's answer, simplifying:

function $(id) { return document.getElementById(id); };

to:

const $ = id=> document.getElementById(id);
查看更多
戒情不戒烟
7楼-- · 2020-02-05 08:13
var $ = document.getElemenyById.bind( document );
查看更多
登录 后发表回答