0

How to code document.querySelector('.class').doSomeThing() with native JavaScript like jQuery methode

exp: $('.class').doSomeThing();

Barmar
  • 741,623
  • 53
  • 500
  • 612
majdi
  • 1
  • http://stackoverflow.com/questions/1933602/how-to-getelementbyclass-instead-of-getelementbyid-with-javascript – Linek Apr 17 '14 at 14:05
  • 1
    If you want to mess with host objects, you should check out the original [*prototype.js*](http://prototypejs.org) (the one that used to modify DOM object prototypes) and also [*What's wrong with extending the DOM*](http://perfectionkills.com/whats-wrong-with-extending-the-dom/). That's not to dissuade you from having a go, just to open your eyes to the pitfalls. – RobG Apr 17 '14 at 23:23

4 Answers4

1
Element.protototype.doSomething = function( passedFunction ){        
    passedFunction.call( this );

    return this;
}

To work with querySelectorAll as well, you would need to assign the function to NodeList.prototype.doSomething too.

Barney
  • 16,181
  • 5
  • 62
  • 76
0

Implement a prototype of the Element object.

Element.prototype.doSomething = function(){
  // do something
}
Amit Joki
  • 58,320
  • 7
  • 77
  • 95
0

If I understood right:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title> Bla! </title>
        <script type='text/javascript'>
          function SayB1(data) {
            alert (data);
          }
          function Init() {
              var buttons = document.getElementsByClassName('button1');
              for (var i in buttons) {
                  buttons[i].onclick = function() {
                      SayB1(this.innerHTML);
                  };
              }
          }
        </script>
    </head>
    <body onload='Init();'>
        <button class='button1'> B1 -1 </button>
        <button class='button1'> B1 -2 </button>
        <button class='button2'> B2 -1 </button>
        <button class='button2'> B2 -2 </button>
        <button class='button1'> B1 -3 </button>
    </body>
</html>
Guy Dafny
  • 1,709
  • 1
  • 14
  • 25
0

There is multiple way of doing a jQuery like plugin. Here one way i like :

(function(scope, name, undefined){
    scope[name] = function(selector){
        return new Plugin(selector);
    }

    function Plugin(selector){
        buildArrayLike(this, selector)
    }
    function buildArrayLike(obj, selector){
        var el = document.querySelectorAll(selector);
        for(var c = 0; c < el.length; c++) obj[c] = el[c];
        obj.length = el.length;
    }

    Plugin.prototype = {
        constructor : Plugin,
        method : function(){
            alert(this.length);
            return this; //For chaining;
        }
    }
})(window, '$')



console.log($('div'));

$('div').method();

Fiddle : http://jsfiddle.net/Rw5BJ/

Karl-André Gagnon
  • 33,662
  • 5
  • 50
  • 75