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>

click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Creating a div element in jQuery

Adblocker detected! Please consider reading this notice.

We've detected that you are using AdBlock Plus or some other adblocking software which is preventing the page from fully loading.

We don't have any banner, Flash, animation, obnoxious sound, or popup ad. We do not implement these annoying types of ads!

We need money to operate the site, and almost all of it comes from our online advertising.

Please add wikitechy.com to your ad blocking whitelist or disable your adblocking software.

×