user1050619
user1050619

Reputation: 20856

Create a new div using jQuery

Im trying to create a new div using Jquery but unfortunately its not being displayed on my html page.

jsfiddle

html/css/js code

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    <style>
      #main_container{
        background-color:red;
        height:100px;
        width:200px
      }
    </style>

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
    $(document).ready(function(){
      var main_container = $("#mainViewContainer");
      $('#mainViewContainer').append($('<div id="table_layout" />')
          .append($('<table id="table_set"/>')
          .append('<thead><tr> <th>ID</th><th>Name</th> <th>DOB</th>  <th>Date Enrolled</th>   </tr></thead>')));

      main_container.appendTo(document.body)
    });
    </script>
  </head>
  <body>
  </body>
</html>

Upvotes: 2

Views: 150

Answers (3)

Bas van Dijk
Bas van Dijk

Reputation: 10713

You should change:

var main_container = $("#mainViewContainer");

into

var main_container = $("<div/>").attr("id", "mainViewContainer");

This creates a new div with the id specified.

$("#mainViewContainer") returns the element with the id mainViewContainer instead of creating an element.

Fiddle

Upvotes: 1

Ionică Bizău
Ionică Bizău

Reputation: 113355

To create the div use:

var main_container = $("<div>").attr("id", "mainViewContainer");

Your code becomes:

$(document).ready(function(){
    var main_container = $("<div>").attr("id", "mainViewContainer");
    main_container.append($('<div id="table_layout" />')
            .append($('<table id="table_set"/>').
                    append('<thead><tr> <th>ID</th><th>Name</th> <th>DOB</th>  <th>Date Enrolled</th>   </tr></thead>')));

    main_container.appendTo(document.body)
});

JSFIDDLE

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Since you are appending mainViewContainer to body, I assume you don't have element with id mainViewContainer in your dom.

So first you need to create a new element with the said id, then append contents to it after that add the element to the document as given below

$(document).ready(function () {
    //create a new div with id mainViewContainer
    var main_container = $('<div id="mainViewContainer"></div>');
    //append new elements to mainViewContainer
    main_container.append($('<div id="table_layout" />')
        .append($('<table id="table_set"/>').
    append('<thead><tr> <th>ID</th><th>Name</th> <th>DOB</th>  <th>Date Enrolled</th>   </tr></thead>')));

    //append mainViewContainer to body
    main_container.appendTo(document.body)
});

Demo: Fiddle

Upvotes: 0

Related Questions