views:

57

answers:

2

Hi there,

I wonder if anyone can explain this:

$(document).ready(function() {
        var popup = $('<div id="popup"><div class="popup-content"></div></div>');
        var popupContent = popup.children('div');
        var overlay = $('<div id="overlay"></div>');

        console.log(popup);
        console.log(popupContent);
        console.log(overlay);
        console.log(overlay.add(popup).appendTo('body'));
    });

I've added some debugging in there in case you want to test it.

I don't understand why only the overlay gets appended when appendTo() is being called on a jQuery object containing two elements?

Any help would be much appreciated.

+1  A: 

My guess is it has something to do with the overlay jQuery object having not been added to the DOM yet. The jquery doc on .add says:

"Given a jQuery object that represents a set of DOM elements, the .add() method constructs a new jQuery object from the union of those elements and the ones passed into the method." - http://api.jquery.com/add/

Your overlay is not a set of DOM elements yet. Can you just use append?:

overlay.append(popup).appendTo('body')
fehays
+1  A: 

But I've just found that removeing the id from the overlay fixes the issue:

$(document).ready(function() {
        var popup = $('<div id="popup"><div class="popup-content"></div></div>');
        var popupContent = popup.children('div');
        var overlay = $('<div></div>');

        console.log(popup);
        console.log(popupContent);
        console.log(overlay);
        console.log(overlay.add(popup).appendTo('body'));
    });

I don't think it should be relevant whether the nodes are on the DOM or not yet as .add() is just combining two jQuery objects.

This is making no sense...

Richard
That is strange. If you pass an object to set the ID, it works. `var overlay = $('<div/>',{id:'overlay'});` Odd.
patrick dw
Yeah I noticed that too, surely the return value of $('<div id="overlay"></div>'), $('div', {id: 'overlay'}) and $('<div></div>') are the same... a jQuery object. (apart from the last one wouldn't have an ID attribute).
Richard
That is strange. Maybe drop a post over on the jquery forums. Sounds kinda bugish... :/
fehays
I've posted a simpler version on the jQuery forum: http://forum.jquery.com/topic/jquery-add-or-appendto-bug
Richard