Reputation: 3639
I know that jQuery.extend can be used to add by own custom methods to an object such as a DOM element but Prototype's Element.extend adds all the DOM element helper methods to the object. It is that functionality that I am after.
For instance
this.panel = document.createElement('div');
I want this.panel to be a reference to that new div but also have the handy element wrapper methods attached to it.
I can get something close by wrapping the call to createElement with jQuery()
this.panel = jQuery(document.createElement('div'));
but that returns an array of one. I just want the element.
What do others do?
TIA
Pat Long
Upvotes: 2
Views: 3558
Reputation: 36140
jQuery policy is to never extend native DOM objects.
Wrapping an element inside a jQuery is the way to go. The result is not an array, it is a jQuery object (similar to an array) but with the extended jQuery methods available.
As a hint, if you want to create elements, you can use jQuery HTML parsing feature, it allows to create complex DOM tree more easily than using DOM create methods.
Maybe you want something like that
// Creates a DIV node with some attributes and text inside, and append it to the body
this.panel = jQuery('<div class="myClass" id="myPanel">My panel</div>').appendTo('body');
Upvotes: 5
Reputation: 32129
You can select one element in the jQuery object using:
$(selector).eq(0): //this will select the first element
So in your case:
this.panel = $(document.createElement('div')).eq(0);
But you could also do:
this.panel = $('<div></div>');
That will do the same.
Also if you want to extend the jquery functionality:
jQuery.fn.myOwnFunction = function(){
this.each( function() {
alert($(this).attr('name'));
}
}
Then if you do something like this:
<input name='bla'>
<input name='foo'>
$('input').myOwnFunction();
will alert: 'bla' and then 'foo'
Upvotes: 0