Q:

How to Create a DIV Element in jQuery

0

How to Create a DIV Element in jQuery

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Use the jQuery append() Method

You can simply use the append() method to dynamically create an element such as a <div> at the end of the selected element in jQuery. Similarly, you can use the prepend() to create or insert element at the beginning. Take a look at the following example to see how this works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Create HTML Elements Using jQuery</title>
<style>
    .container{
        padding: 20px;
        background: #f2f2f2;
        border: 5px solid #aaa;
    }
    .content{
        padding: 10px;
        border: 3px solid orange;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    // Insert elements on click of the button
    $("button").click(function(){
        // Creating a div element at the end
        $(".container").append('<div class="content">Appended DIV</div>');   
 
        // Creating a div element at the start
        $(".container").prepend('<div class="content">Prepended DIV</div>'); 
    });    
});
</script>
</head>
<body>
    <div class="container">
        <h1>This is a heading</h1>
        <p>This is a paragraph.</p>
        <p><button type="button">Insert DIV</button></p>
    </div>
</body>
</html>

jQuery also provide methods, like before() and after() to create the elements before or after the selected elements

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Convert a JS Object to an Array Using jQuer... >>
<< How to Submit a Form Using jQuery...