tags:

views:

68

answers:

2

I'm trying to use jQuery's append() method to append common content to set of div's as follows:

$("#horizontal_menu").append(menu);
$("#vertical_menu").append(menu);

What I'm finding is that the content (in this case, menu) is getting appended to vertical_menu but not horizontal_menu. Does appending to one <div> preclude you from appending that content to another <div>?

+1  A: 

Does appending to one preclude you from appending that content to another ?

With respect to [jQuery wrapped] DOM elements, yes. Under the hood jQuery calls appendChild, which when called multiple times with the same element simply moves it from its current position to the new position.

You can try cloning to make a copy:

var $menu = $(menu);
$("#horizontal_menu").append($menu.clone());
$("#vertical_menu").append($menu.clone());

You can pass true to clone() if you want event handlers to be copied over as well.

Roatin Marth
Ah. I didn't realize that append() was functionally a move rather than a copy.
quanticle
+1  A: 

You can flip it around using .appendTo() like this:

menu.appendTo("#horizontal_menu, #vertical_menu");

If menu isn't a jQuery object just wrap it:

$(menu).appendTo("#horizontal_menu, #vertical_menu");

Currently what's happening is it does get appended, or more accurately moved to #horizontal_menu, then gets immediately moved again. Passing a selector or multiple elements to .appendTo() makes it clone and append to each internally.

Nick Craver
Thanks. This works, and it doesn't require me to assign a class to my <div>s specifically for use as a jQuery selector.
quanticle