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?
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');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With