JQuery Append To Multiple Elements Fails

15,400

Solution 1

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.

Solution 2

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.

Share:
15,400
quanticle
Author by

quanticle

Updated on June 12, 2022

Comments

  • quanticle
    quanticle almost 2 years

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

  • quanticle
    quanticle over 13 years
    Ah. I didn't realize that append() was functionally a move rather than a copy.
  • quanticle
    quanticle over 13 years
    Thanks. This works, and it doesn't require me to assign a class to my <div>s specifically for use as a jQuery selector.
  • Pratik Bothra
    Pratik Bothra over 9 years
    This isn't working....It only appends to the first one -: #horizontal menu. Has this changed in recent versions of jQuery?
  • Nick Craver
    Nick Craver over 9 years
    @PratikBothra which version of jQuery are you on? A quick fiddle test shows it still working here: jsfiddle.net/81ea73aj
  • Pratik Bothra
    Pratik Bothra over 9 years
    @NickCraver - Any idea why the code is failing inside my jsfiddle?
  • Christhofer Natalius
    Christhofer Natalius about 8 years
    @Pratik Bothra sorry if it is too late, chek this quick fix jsfiddle.net/LzaLhe3p/1
  • Pratik Bothra
    Pratik Bothra about 8 years
    @Christ Lol, I couldn't even remember why I had this problem :-)
  • van_folmert
    van_folmert about 7 years
    this won't work when you're appending to multiple jQuery objects - they need to be passed as an array