Georgi Antonov
Georgi Antonov

Reputation: 1641

Dynamically create div with img and append it to existing div

So I'm trying to create HTML div element via createPost() function

Then add HTML img element via addElements() function

And then append the div to already created div with id="posts-div"

But it seems something is wrong in my script because the div is not appended

This whole script is wrapped inside $(document).ready of course

var testimg = 'images/1.png'
function createPost(){
    var post = document.createElement('div');
    post.className += 'col-md-3';
    post.className += 'col-sm-6';
    post.className += 'col-xs-12';
    post.className += 'post';
}          
function addElements(){
    var img = document.createElement('img');
    img.src = testimg;
    img.alt = 'post';
    img.className += 'img-responsive';
    $(post).append(img);    
}
createPost();
addElements();     
$('#posts-div').append(post);

Upvotes: 1

Views: 997

Answers (3)

DinoMyte
DinoMyte

Reputation: 8858

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/

Upvotes: 3

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

Since you're using jQuery your code could be :

var testimg = 'images/1.png'

var post = '<div class="col-md-3 col-sm-6 col-xs-12 post"></div>';
var img = '<img src="'+testimg+'" alt="post" class="img-responsive" '/>;

$(post).append(img);
$('#posts-div').append(post);

Hope this helps.

Upvotes: 0

Maccath
Maccath

Reputation: 3956

The variable post is defined inside the createPost() function, which means that it is out of scope when you try to append it - it only exists within the createPost() function. Define post outside of the createPost() function, and it will become globally accessible, and it should work.

e.g.

 var testimg = 'images/1.png'
 var post;
 function createPost(){
     post = document.createElement('div');
     post.className += 'col-md-3';
     post.className += 'col-sm-6';
     post.className += 'col-xs-12';
     post.className += 'post';
 }          
 function addElements(){
     var img = document.createElement('img');
     img.src = testimg;
     img.alt = 'post';
     img.className += 'img-responsive';
     $(post).append(img);    
 }
 createPost();
 addElements();     
 $('#posts-div').append(post);

Upvotes: 1

Related Questions