Create <Div> and Append <Div> Dynamically

Create div and append div dynamically

Use the same process. You already have the variable iDiv which still refers to the original element <div id='block'> you've created. You just need to create another <div> and call appendChild().

// Your existing code unmodified...
var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

// Now create and append to iDiv
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

http://jsfiddle.net/W4Sup/1/

The order of event creation doesn't have to be as I have it above. You can alternately append the new innerDiv to the outer div before you add both to the <body>.

var iDiv = document.createElement('div');
iDiv.id = 'block';
iDiv.className = 'block';

// Create the inner div before appending to the body
var innerDiv = document.createElement('div');
innerDiv.className = 'block-2';

// The variable iDiv is still good... Just append to it.
iDiv.appendChild(innerDiv);

// Then append the whole thing onto the body
document.getElementsByTagName('body')[0].appendChild(iDiv);

Dynamically create div with img and append it to existing div

Here's another version which I believe is a better way.

var testimg = 'images/1.png';
var post;
var img;
function createPost(){
post = $('<div/>',{ class:"col-md-3 col-sm-6 col-xs-12 post" }).appendTo("#posts-div");
}

function addElements(){
img = $('<img/>',{ src:testimg , alt:'post',class:'img-responsive' }).appendTo(post);
}
createPost();
addElements();

Example : https://jsfiddle.net/DinoMyte/b8tetvhh/1/

Dynamically create div and into a static div

Your code have many issues. Try like this:

var elm = document.createElement('div');
elm.className = 'some_demo_class'; // add all your css styles in a class
var x = document.getElementById("staticDiv");
x.appendChild(elm);

How to add div dynamically inside a div by class - Jquery

To add an info div into every class using jQuery, simply use:

$( ".dynamic" ).append( "<div class='info'>info</div>" );

The JSFiddle demonstrates it.

If you want to continually check for .dynamic classes, you can use something like this:

$(document).ready(setInterval(function(){
$( ".dynamic" ).append( "<div class='info'>info</div>" );
}, 1000));

In the above case, you are checking for .dynamic classes every 1000ms (1 second).

Hope this helps.



Related Topics



Leave a reply



Submit