Make alias to document.getElementById in Javascrip

2020-02-05 07:35发布

问题:

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

Thanks

回答1:

Possibly the easiest/shortest way:

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


回答2:

var $ = document.getElemenyById.bind( document );


回答3:

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.



回答4:

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);


回答5:

function $( s ) {
    return document.getElementById( s ) ? document.getElementById( s ) : "";
}

$( "myId" );

This assumes you only want to use the dollar function (selector) to get an ID. I didn't test that, but it should work.

The last time I looked at the core of jQuery, it took a string as an argument and then used a regular expression to determine what kind of selector it was.



回答6:

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.



回答7:

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.