Reputation: 1641
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
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
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
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