tags:

views:

1279

answers:

2

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

A: 

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'

Pim Jager
+5  A: 

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');
Vincent Robert
Thanks for making it clear that "jQuery policy is to never extend native DOM objects", shame I liked Prototyopes approach.I really don't like using jQuery to parse a dynamic HTML string. It just seems so old school, like using innerHtml
Pat Long - Munkii Yebee
Yes it looks old school, I agree. But it is so often simpler than actually creating every DOM nodes by hand and linking them together. And contrary to innerHtml, you actually get a nice DOM tree because jQuery does all the parsing for you.
Vincent Robert
and the code is also a LOT faster if you add a lot of nodes as one string
wheresrhys