Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Append To Multiple Elements Fails

Tags:

html

jquery

xhtml

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>?

like image 857
quanticle Avatar asked Sep 03 '10 13:09

quanticle


2 Answers

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.

like image 96
Nick Craver Avatar answered Oct 27 '22 16:10

Nick Craver


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.

like image 43
Roatin Marth Avatar answered Oct 27 '22 17:10

Roatin Marth