javascript tutorial - [Solved-5 Solutions] Creating a div element in jQuery - javascript - java script - javascript array
Problem:
How do I create a div element in jQuery?
Solution 1:
First select the parent element with something like
$("#id"), $("element") or $(".class")
click below button to copy the code. By JavaScript tutorial team
Then use the .append("<div>foo</div>")
function. Alternatively, you can use the .html()
as mentioned in a different answer.
$("#foo").append("<div>hello world</div>")
click below button to copy the code. By JavaScript tutorial team
Solution 2:
jQuery('<div/>', {
id: 'foo',
href: 'http://wikitechy.com',
title: 'Become a Tech Professional',
rel: 'external',
text: 'Go to Kashiv Info Tech!'
}).appendTo('#mySelector')
click below button to copy the code. By JavaScript tutorial team
Solution 3:
d = document.createElement('div');
$(d).addClass(classname)
.html(text)
.appendTo($("#myDiv")) //main div
.click(function () {
$(this).remove();
})
.hide()
.slideToggle(300)
.delay(2500)
.slideToggle(300)
.queue(function () {
$(this).remove();
});
click below button to copy the code. By JavaScript tutorial team
Solution 4:
div = $("<div>").html("Loading......");
$("body").prepend(div);
click below button to copy the code. By JavaScript tutorial team
Solution 5:
HTML part:
<div id="targetDIV" style="border: 1px solid Red">
This text is surrounded by a DIV tag whose id is "targetDIV".
</div>
click below button to copy the code. By JavaScript tutorial team
JavaScript code:
//Way 1: appendTo()
<script type="text/javascript">
$("<div>hello wikitechy users</div>").appendTo("#targetDIV"); //appendTo: Append at inside bottom
</script>
//Way 2: prependTo()
<script type="text/javascript">
$("<div>Hello, wikitechy users</div>").prependTo("#targetDIV"); //prependTo: Append at inside top
</script>
//Way 3: html()
<script type="text/javascript">
$("#targetDIV").html("<div>Hello, wikitechy users</div>"); //.html(): Clean HTML inside and append
</script>
//Way 4: append()
<script type="text/javascript">
$("#targetDIV").append("<div>Hello, wikitechy users</div>"); //Same as appendTo
</script>