简体   繁体   中英

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);

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/

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.

eg

 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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM