Reputation: 2228
I am trying to add two div elements to my html body, I start by creating the div elements assigning a unique id and storing them in two variables.
var a = $('div').attr('id', 'container');
var b= $('div').attr('id', 'selectable');
$(a).appendTo('body');
$(b).appendTo('body);
The problem is when I add them to the body, I notice only one div element is actually being appended to the body. Upon further inspection, I noticed that the content in variable b is being copied to variable a, so variable a and b both refer to the same div with ID selectable.
How do I create two unique div elements to be appended to the html body?
Upvotes: 3
Views: 3375
Reputation: 314
Quick hack?
This code SELECTS matching elements from the DOM
var a = $('div').attr('id', 'container');
To store a certain div in a variable, use jQuery's .clone();
method.
So for example
var div_copy = $('div').clone(); //Saved for later use
Upvotes: 0
Reputation: 20598
This searches the dom for all div elements:
$('div');
So the following code is applying the id of 'selectable' to all div elements.
var a = $('div').attr('id', 'container');
var b = $('div').attr('id', 'selectable');
To create an element in jQuery, you need to have a string that begins with '<'. To get the result you want, you probably want to do the following:
var a = $('<div/>').attr('id', 'container');
a.appendTo('body');
You could also do:
var a = $('<div id="container" />').appendTo('body');
Upvotes: 4
Reputation: 27012
You are selecting divs, not creating them.
var a = $('div').attr('id', 'container');
var b = $('div').attr('id', 'selectable');
Should be:
var a = $('<div/>').attr('id', 'container');
var b = $('<div/>').attr('id', 'selectable');
Upvotes: 9