Creating a Div Element in Jquery

Creating a div element in jQuery

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

$('#parent').append('<div>hello</div>');    
// or
$('<div>hello</div>').appendTo('#parent');

Alternatively, you can use the .html() or .add() as mentioned in a different answer.

The preferred way of creating a new element with jQuery

The first option gives you more flexibilty:

var $div = $("<div>", {id: "foo", "class": "a"});
$div.click(function(){ /* ... */ });
$("#box").append($div);

And of course .html('*') overrides the content while .append('*') doesn't, but I guess, this wasn't your question.

Another good practice is prefixing your jQuery variables with $:

Is there any specific reason behind using $ with variable in jQuery

Placing quotes around the "class" property name will make it more compatible with less flexible browsers.

Creating div element using jquery and adding inner html

You can also do something like this:

js

$("<div/>",{
id: "a",
text:"sadsad",
style:"background-color:red;height:50px;",
class: "classA"
}).appendTo("body");

fiddle

Creating a div using jquery with style tag

You need to use css not style

$(document).ready(function() {  var ss = {    id: "foo",    class: "attack",    dataa: "hhh",    css: {      "color": "red"    }  };  var $div = $("<div>", ss);  $div.html("dfg");  $("body").append($div);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

jQuery create new div with ID?

Just set the attribute when you're creating it

$(document.createElement('div')).attr('id', 'theID')//rest of code

JQuery: Create a div as parent and add existing elements to it

Try this, DEMO

  $(document).ready(function () {        var mycontent = '';        $("#cont").children("a").each(function (index) {            var cc = $(this).html();            if (index % 4 == 0) {                mycontent += '</div><div id="abc' + index + '">';                mycontent += "<a href=''>" + $(this).html() + "</a>";            }            else {                mycontent += "<a href=''>" + $(this).html() + "</a>";            }        });        $("#cont").find('a').remove();        $("#cont:first .row").append(mycontent);    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script><div class="container" id="cont">    <div class="row">        <div class="col-lg-12">            <h1 class="page-header">My Page Header</h1>        </div>    </div>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a>    <a>....</a></div>

Creating a new div for each element for two different arrays using JQuery

I think the issue just had to do with ' vs ". Make sure when you have to mix and match them, use one to start/stop your string and the other inside the string (or you can escape the characters but I find that more difficult to read).

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="box-cart-products"></div>
<script> var itemImages = ["image1", "image2", "image3"] var itemNames = ["name1", "name2", "name3"]
$(itemImages).each(function(i, e) { $(".box-cart-products").append( '<div class="box-cart-product"> <div class="box-cart-product-image"><img src="' + itemImages[i] + '"/> </div> <div class="box-cart-product-name"> <span>' + itemNames[i] + '</span></div></div>' ) })</script>

How to create div with text using jQuery?

Instead of using .text(), try using .html().

How to build big div structures in JavaScript (JQuery)?

For anything complex, use a HTML template. That can be as simple as a dummy script block, with an id, that uses an unknown type so the browser ignore it (I use text/template). You then just use the inner html() of the element to create the new structure. Much easier to read/maintain and less error prone

Example html:

<script id="mytemplate" type="text/template">
<div class="Post">
<div class="PostHead">
<span class="profilePicture">
<img src="../Profiles/Tom.jpg" />
</span>
<span class="userName">Tom</span>
<span class="postTime">10 minutes ago</span>
</div>
<div class="PostBody">
<p>Hey Tom, great work at the presentation last week. Well done!</p>
</div>
</div>
<script>

then create one with:

$('.PostWrapper').append($('#mytemplate').html());

note: If they need dynamic values anywhere, use text replacement markers in the template and string replaces.

e.g.

<script id="mytemplate" type="text/template">
<div class="Post">
<div class="PostHead">
<span class="profilePicture">
<img src="{image}" />
</span>
<span class="userName">{name}</span>
<span class="postTime">{posted}</span>
</div>
<div class="PostBody">
<p>{notes}</p>
</div>
</div>
<script>

Or simply add those details once the template has been added to the DOM.

jquery append() is creating two div elements

Since you have used angularjs, use a angularjs solution

<div class="content-wrapper" ng-controller="mission_visionCtrl">
<div class="container-fluid">
<div id="header-wrapper" class="container">
<div id="header" class="container">
<div id="logo">
<h1 class="page-head-line" id="visionh"><a>Vision</a></h1>
<p id="visionp"><a rel="nofollow">{{visiontext}}</a></p>
</div>
</div>
</div>
<div class="row" id="missionstart">
<div id="{{mission.id}}" ng-class="missioncount[missions.length]" ng-repeat="mission in missions">
<div class="dashboard-div-wrapper" ng-class="bkclr[$index]">
<h1>{{mission.missionInfo}}</h1>
<div class="progress progress-striped active">
<div class="progress-bar" ng-class="progressbar[$index]" role="progressbar" aria-valuenow="80" aria-valuemin="0" aria-valuemax="100" style="width: 80%"></div>
</div>
<ul class="unorderedlist"></ul>
</div>
</div>
</div>
</div>
</div>

then

mission_vision_mod.controller('mission_visionCtrl', ['$scope', '$http', function ($scope, $http) {
$scope.visiontext = "Here is the content of vision";
$scope.bkclr = ['bk-clr-one', 'bk-clr-two', 'bk-clr-three', 'bk-clr-four'];
$scope.progressbar = ['progress-bar-warning', 'progress-bar-danger', 'progress-bar-success', 'progress-bar-primary'];
$scope.missioncount = ['col-md-0', 'col-md-12', 'col-md-6', 'col-md-4', 'col-md-3', 'col-md-2.5', 'col-md-2'];

$http.get('m_id.json').success(function (data) {
$scope.missions = data;
$scope.len = data.length;
});

$scope.missions = data;
$scope.len = data.length;


}]);


Related Topics



Leave a reply



Submit