Invoke a custom method on a DOM element

4.4k views Asked by At

I want to invoke a custom method on a DOM element

like this :

<div id="MyObject">
    <!-- some elements -->
</div>

<script>
    function doSomething() {
        // do something with input DOM element
    }

    $("MyObject").doSomething();
</script>

How can I develop this problem? Is it necessary to use jQuery or not?

3

There are 3 answers

3
Cymen On BEST ANSWER

You do not need to use jQuery. You can use document.getElementById('MyObject') to get a reference to the DOM node.

To run your doSomething function on it, you would need to add a node parameter to it something like this:

function doSomething(input) {
  // do something with input DOM element
}

doSomething(document.getElementById('MyObject'));

To have it chained, you would need to add to the Element interface which all DOM nodes implement (rereading, I meant inherit from). If you go that way, you could do:

Element.prototype.doSomething = function() {
  alert(this);
}

document.getElementById('MyObject').doSomething();

JSFiddle: http://jsfiddle.net/6Lyb4b9p/

MDN: getElementById

1
Emad Armoun On

I found the answer by myself.

I can practice in this way :

<script>
    (function ($) {
        $.fn.doSomething = function () {
            // do something like this
            $(this).append("Hello Object");
        }
    } (jQuery));

    $("#MyDOMElement").doSomething();
</script>
0
Arun P Johny On

Without jQuery, you could do something like

if (typeof $ != 'function') {
  //create a function $ which will return the element with said id
  window.$ = function(id) {
    return document.getElementById(id);
  }
}

//Add a method to the Elemen prototype so you can call it on any element object
Element.prototype.doSomething = function() {
  this.innerHTML = 'hi from inner';
}

$('MyObject').doSomething();
<div id="MyObject">
  <!-- some elements -->
</div>