Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Storing html elements created by Jquery in variable

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?

like image 302
lboyel Avatar asked Feb 04 '26 17:02

lboyel


2 Answers

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'); 
like image 154
Jason P Avatar answered Feb 06 '26 05:02

Jason P


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');
like image 25
kzh Avatar answered Feb 06 '26 05:02

kzh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!