Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invoke a custom method on a DOM element

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?

like image 694
Emad Armoun Avatar asked Sep 15 '25 11:09

Emad Armoun


1 Answers

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

like image 122
Cymen Avatar answered Sep 18 '25 09:09

Cymen