Reputation: 20856
Im trying to create a new div using Jquery but unfortunately its not being displayed on my html page.
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
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.
Upvotes: 1
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)
});
Upvotes: 1
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