Creating an empty jQuery object

View: New views
10 Messages — Rating Filter:   Alert me  

Creating an empty jQuery object

by Danny Wachsstock :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

I've been using jQuery for a few months now, trying to convert all my hand-rolled javascript and came across a minor problem that I could not find documented anywhere:
I want to create DOM elements and add them into a jQuery object, as in;

var result = [empty jQuery object];
$.each(...
  var element = ...;
  result.add(element);
);

But how to create an empty jQuery? Scouring the source code, I eventually hit upon $([]), but this is nowhere documented. Is there a better way?
Is there a good reason $() should return $(document) rather than an empty jQuery?

Daniel Wachsstock
http://youngisrael-stl.org

Re: Creating an empty jQuery object

by Sam Collett :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 16/02/07, Danny Wachsstock <d.wachss@...> wrote:

>
> I've been using jQuery for a few months now, trying to convert all my
> hand-rolled javascript and came across a minor problem that I could not find
> documented anywhere:
> I want to create DOM elements and add them into a jQuery object, as in;
>
> var result = [empty jQuery object];
> $.each(...
>   var element = ...;
>   result.add(element);
> );
>
> But how to create an empty jQuery? Scouring the source code, I eventually
> hit upon $([]), but this is nowhere documented. Is there a better way?
> Is there a good reason $() should return $(document) rather than an empty
> jQuery?
>
> Daniel Wachsstock
> http://youngisrael-stl.org
>
> --

I found that out the hard way as well, so perhaps it should be
documented. I think searching for a class that does not exist (
$("atag.nonexistentclass") ) will also return an empty jQuery object.

As for changing $() to not return $(document), that may be a bad idea
as it helps reduce the amount of code to write, plus may break some
plugins.

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Creating an empty jQuery object

by nileshp :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

yah it think $() is the shortcut for $(document), i seen it listed some place in the docs,

maybe try ...  $(Array()).each()?

 $(Array('')).each(function(i) {   } )

Jquery has a DOM plug-in , that allows your to store dom in a Object format.

yet i think you can just do something like ..


$('#idContent').add('test').find('a').each(function(){
});

above is just one way, i am sure other jquery users here will give you good suggestion other then above logic.

Nilesh


Re: Creating an empty jQuery object

by Danny Wachsstock :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Yes, $('nonexistent-selector') works, but seems very inelegant. I think $([]) is the best solution, but I'd like to hear from the gurus. How much code depends on $() referring to document?


Sam Collett wrote:
On 16/02/07, Danny Wachsstock <d.wachss@prodigy.net> wrote:
>
> I've been using jQuery for a few months now, trying to convert all my
> hand-rolled javascript and came across a minor problem that I could not find
> documented anywhere:
> I want to create DOM elements and add them into a jQuery object, as in;
>
> var result = [empty jQuery object];
> $.each(...
>   var element = ...;
>   result.add(element);
> );
>
> But how to create an empty jQuery? Scouring the source code, I eventually
> hit upon $([]), but this is nowhere documented. Is there a better way?
> Is there a good reason $() should return $(document) rather than an empty
> jQuery?
>
> Daniel Wachsstock
> http://youngisrael-stl.org
>
> --

I found that out the hard way as well, so perhaps it should be
documented. I think searching for a class that does not exist (
$("atag.nonexistentclass") ) will also return an empty jQuery object.

As for changing $() to not return $(document), that may be a bad idea
as it helps reduce the amount of code to write, plus may break some
plugins.

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/

Re: Creating an empty jQuery object

by malsup :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

> var result = [empty jQuery object];
> $.each(...
>   var element = ...;
>   result.add(element);
> );
>
> But how to create an empty jQuery? Scouring the source code, I eventually

You can just flip the logic around.  Instead of creating an empty
jQuery object and adding elements to it, build the array of elements
and then wrap it in a jQuery object:

var result = [];
$.each(...
        var element = ...;
        result.push(element);
);
var jq = $(result);

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Creating an empty jQuery object

by wycats :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

You know that you can create a DOM Element by doing $("<div></div>"), right? I think that might be a better way to achieve what you're trying to achieve, but I'm not sure. :(

I think $([]) is currently the most elegant way to get an empty object, but this is definitely something that should be pointed out front-and-center.

-- Yehuda

On 2/16/07, Danny Wachsstock <d.wachss@...> wrote:

I've been using jQuery for a few months now, trying to convert all my
hand-rolled javascript and came across a minor problem that I could not find
documented anywhere:
I want to create DOM elements and add them into a jQuery object, as in;

var result = [empty jQuery object];
$.each(...
  var element = ...;
  result.add(element);
);

But how to create an empty jQuery? Scouring the source code, I eventually
hit upon $([]), but this is nowhere documented. Is there a better way?
Is there a good reason $() should return $(document) rather than an empty
jQuery?

Daniel Wachsstock
http://youngisrael-stl.org

--
View this message in context: http://www.nabble.com/Creating-an-empty-jQuery-object-tf3240592.html#a9008167
Sent from the JQuery mailing list archive at Nabble.com.


_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/



--
Yehuda Katz
Web Developer | Wycats Designs
(ph)  718.877.1325
_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Creating an empty jQuery object

by John Resig :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

More code depends on $() referring to document than you might think.
Whenever no context is passed in to a jQuery object, the context is
set to 'document'. That way when you do a .find(), it'll actually find
some relevant elements. Since $() has no context, the context then
defaults to document. Same with doing $("").

If you want an empty set, $([]) is the preferred solution (it's what I
would use, too).

All that being said, however, I somehow suspect that the result that
you're trying to achieve could be done much more easily, in another
way. Can you post your full code for us to look at? I don't think I've
ever seen a true need to have an empty jQuery set returned.

--John

On 2/16/07, Danny Wachsstock <d.wachss@...> wrote:

>
> Yes, $('nonexistent-selector') works, but seems very inelegant. I think $([])
> is the best solution, but I'd like to hear from the gurus. How much code
> depends on $() referring to document?
>
>
>
> Sam Collett wrote:
> >
> > On 16/02/07, Danny Wachsstock <d.wachss@...> wrote:
> >>
> >> I've been using jQuery for a few months now, trying to convert all my
> >> hand-rolled javascript and came across a minor problem that I could not
> >> find
> >> documented anywhere:
> >> I want to create DOM elements and add them into a jQuery object, as in;
> >>
> >> var result = [empty jQuery object];
> >> $.each(...
> >>   var element = ...;
> >>   result.add(element);
> >> );
> >>
> >> But how to create an empty jQuery? Scouring the source code, I eventually
> >> hit upon $([]), but this is nowhere documented. Is there a better way?
> >> Is there a good reason $() should return $(document) rather than an empty
> >> jQuery?
> >>
> >> Daniel Wachsstock
> >> http://youngisrael-stl.org
> >>
> >> --
> >
> > I found that out the hard way as well, so perhaps it should be
> > documented. I think searching for a class that does not exist (
> > $("atag.nonexistentclass") ) will also return an empty jQuery object.
> >
> > As for changing $() to not return $(document), that may be a bad idea
> > as it helps reduce the amount of code to write, plus may break some
> > plugins.
> >
> > _______________________________________________
> > jQuery mailing list
> > discuss@...
> > http://jquery.com/discuss/
> >
> >
>
> --
> View this message in context: http://www.nabble.com/Creating-an-empty-jQuery-object-tf3240592.html#a9010063
> Sent from the JQuery mailing list archive at Nabble.com.
>
>
> _______________________________________________
> jQuery mailing list
> discuss@...
> http://jquery.com/discuss/
>

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Creating an empty jQuery object

by Danny Wachsstock :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

Wow. I leave my computer for 24 hours and I get answers from John Resig, Yehuda Katz and Mike Alsup. I love the jQuery community (and jQuery itself, of course).

Mike:
  Yes, adding to an empty array then jQuery'ing it would work; it's how I originally structured my code. Adding to a jQuery better matches the program logic to what I'm trying to accomplish; my definition of "elegant." I don't have a problem writing $([]); i just wondered if there was a better way.

Yehuda:
  I do know about $('<..html/>'), but my mother always said "Don't hang with those innerHTML kids, you'll learn bad habits." Seriously, I find it very hard to debug the assemble-a-string-and-have-the-interpreter-figure-it-out sort of thing, like innerHTML and eval. I'm not a strict standardista, but using actual code and HTML lets Firebug or the validator find my stupid syntax errors much more easily.

John:
  I believe you on the $() thing; I'll stick to $([]). It clearly could be coded differently, either Mike's way or:
    var result;
    $.each(...
      if (result) result.add(e); else result = e;
    )
but again, I think my way is more elegant.

The original code is my variant of Kevin's DOM creation code (http://mg.to/2006/02/27/easy-dom-creation-for-jquery-and-prototype#comment-294)
(yes, yet another DOM creator):

$.dom = function(){
  var result = $([]), e;
  for (var i = 0; i < arguments.length; ++i){
    if (arguments[i].constructor == String){
      // a string is either a text literal or a tag name of an element.
      // distinguish by the following argument; a tag name will be followed by an Object
      if (arguments[i+1] && arguments[i+1].constructor == Object){
        e = $(document.createElement(arguments[i])).
          attr (arguments[++i]).css(arguments[i].style || {}); // incorporate the attributes Object
        // append children if the next argument is an array
        if (arguments[i+1] && arguments[i+1].constructor == Array) e.append($.dom.apply(null, arguments[++i]));
      }else{
        e = document.createTextNode(arguments[i]);
      }
    }else if (arguments[i].constructor == Array){
      // process the array
      e = $.dom.apply(null, arguments[i]);
    }else{
      // Something else . Let jQuery deal with it
      e = arguments[i];
    } // if
    result = result.add(e);
  }  // for
  return result;
}; // dom

This version allows you to insert pre-existing things in the created elements, like
$.dom('div', {Class: 'x'}, [ 'These are all the P elements:' [$('P')]])
puts $('P') into the new div.

It also lets the attribute object include inline styles, as in
$.dom('div', {id: 'myDiv', style: {border: '1px solid red'}})
by using .css(arguments[i].style || {});

Would it be worth changing .attr to allow this directly?

You can see this in action at http://youngisrael-stl.org ; look at the results from search box on the left column.

i guess you can add that to the list of jQuery sites, too. I'd be flattered.

Thanks for your comments.

Danny
   
John Resig wrote:
More code depends on $() referring to document than you might think.
Whenever no context is passed in to a jQuery object, the context is
set to 'document'. That way when you do a .find(), it'll actually find
some relevant elements. Since $() has no context, the context then
defaults to document. Same with doing $("").

If you want an empty set, $([]) is the preferred solution (it's what I
would use, too).

All that being said, however, I somehow suspect that the result that
you're trying to achieve could be done much more easily, in another
way. Can you post your full code for us to look at? I don't think I've
ever seen a true need to have an empty jQuery set returned.

--John

Re: Creating an empty jQuery object

by Sam Collett :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

On 18/02/07, Danny Wachsstock <d.wachss@...> wrote:
> Yehuda:
>   I do know about $('<..html/>'), but my mother always said "Don't hang with
> those innerHTML kids, you'll learn bad habits." Seriously, I find it very
> hard to debug the assemble-a-string-and-have-the-interpreter-figure-it-out
> sort of thing, like innerHTML and eval. I'm not a strict standardista, but
> using actual code and HTML lets Firebug or the validator find my stupid
> syntax errors much more easily.
>

I may not be a guru (but have been using it for a long time), but
while jQuery does use innerHTML, it does in a way to work around
limitations in the browsers. Without it, I don't think you would be
able to create select options or table cells/rows via the $("<html>")
method.

All of the supported browsers recognise innerHTML and I can't see it
going away any time soon, or any new browser shipping without support
for it as so many sites rely on it to work. Much like how XHTML strict
(served with correct content type) will likely never see widespread
adoption. I think HTML 5 (http://blog.whatwg.org/faq/) is more likely
to take off IF Internet Explorer 8 adopts it (as it simply expands on
what people use now, and is not a complete break from HTML like XHTML
2 is), but as Microsoft are pushing XAML that may not happen.

_______________________________________________
jQuery mailing list
discuss@...
http://jquery.com/discuss/

Re: Creating an empty jQuery object

by Danny Wachsstock :: Rate this Message:

Reply to Author | View Threaded | Show Only this Message

This may be hijacking the thread, so I'll keep it brief. i agree that innerHTML is useful, and it is a de-facto standard (like AJAX). I also agree that whatwg's work is much closer to reality than w3g's, and like I said, I'm not a fanatic standardista. My point is that it's harder to debug complicated strings than language constructs, since the language will tell you there's a syntax error right away. As in
$("<div class='first'><div><div>"+"</div></div>");
It would take me forever to find that I missed a closing div, and keeping track of all the quotes is well-nigh impossible. To use my function,
$.dom('div', {Class: 'first'}, ['div',{},['div',{},['span', {style: {color: getColor()}}]]])
and if I screw up a parenthesis or brace, Firebug will tell me right away.

For simple things ($("Hello") I'll use innerHTML, and certainly if someone else is taking responsibility for generating the string (as in AJAX), there's nothing easier than innerHTML.

Danny

Sam Collett wrote:
I may not be a guru (but have been using it for a long time), but
while jQuery does use innerHTML, it does in a way to work around
limitations in the browsers. Without it, I don't think you would be
able to create select options or table cells/rows via the $("<html>")
method.

All of the supported browsers recognise innerHTML and I can't see it
going away any time soon, or any new browser shipping without support
for it as so many sites rely on it to work. Much like how XHTML strict
(served with correct content type) will likely never see widespread
adoption. I think HTML 5 (http://blog.whatwg.org/faq/) is more likely
to take off IF Internet Explorer 8 adopts it (as it simply expands on
what people use now, and is not a complete break from HTML like XHTML
2 is), but as Microsoft are pushing XAML that may not happen.

_______________________________________________
jQuery mailing list
discuss@jquery.com
http://jquery.com/discuss/