Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .add method seemingly not working?

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.

like image 759
Richard Avatar asked Sep 15 '10 22:09

Richard


1 Answers

.add() doesn't modify the existing object, it returns a new object with the values in it. So you aren't appending the object you think you are.

This portion of code does NOT modify the overlay object: overlay.add(popup) Rather, it creates a new object, but since there is no reference to that new object, it is immediately lost--there is no way you can use it. The overlay object itself is unchanged.

You should do something like this instead:

overlay = overlay.add(popup);
overlay.appendTo('body');
like image 169
Shawn Avatar answered Sep 22 '22 03:09

Shawn