Reputation: 2099
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?
Upvotes: 4
Views: 4700
Reputation: 14419
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
Upvotes: 10
Reputation: 388316
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>
Upvotes: 4
Reputation: 2099
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>
Upvotes: 1