Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append the same variable twice?

I am trying to append the same variable twice but it appears the code only works on the second one.

var test=document.createElement('option');               
test.innerHTML='some data';

      $('#data1').append(test);
      $('#data2').append(test);

I want to append the variable test twice WITHOUT creating another variable. Thanks a lot!

like image 366
Rouge Avatar asked Jun 28 '26 23:06

Rouge


2 Answers

Try putting in same selector like below,

DEMO: http://jsfiddle.net/mrMva/

$('#data1, #data2').append(test);

As Felix pointed out from jQuery docs for .append

If there is more than one target element, however, cloned copies of the inserted element will be created for each target after the first.

like image 120
Selvakumar Arumugam Avatar answered Jun 30 '26 11:06

Selvakumar Arumugam


Clone it:

  $('#data1').append(test);
  $('#data2').append(test.cloneNode(true));

Or just do this, and jQuery will clone it for you:

$('#data1, #data2').append(test);

Or like this:

$("<option>some data</option>").appendTo('#data1, #data2');
like image 45
I Hate Lazy Avatar answered Jun 30 '26 11:06

I Hate Lazy