Issue
I'm new to JavaScript, so apologies if any of my terminology is wrong or confusing - I'm still trying to learn! I'm trying to create a page that adds the image from an array to a div that's created on page load. At best I can get it to show the path of the image, but I can't get it to show the actual image. This is the code I've got so far (in this, nothing at all is showing in the element, not even the path)
HTML:
<main>
<div id="style-container">
</div>
</main>
JavaScript:
const styles = [
{
description: 'Alunar Gold Leather Sling Back Heels',
code: 'ALUNAR GDL',
img: 'static/images/ALUNAR-GDL.jpg'
},
{
description: 'Alunar Green Leather Sling Back Heels',
code: 'ALUNAR GNL',
img: 'static/images/ALUNAR-GNL.jpg'
},
{
description: 'Alunar Silver Leather Sling Back Heels',
code: 'ALUNAR SLL',
img: 'static/images/ALUNAR-SLL.jpg'
},
{
description: 'Alunar White Leather Sling Back Heels',
code: 'ALUNAR WTL',
img: 'static/images/ALUNAR-WTL.jpg'
},
]
const createStyle = () => {
let i;
for (i = 0; i < styles.length; i++) {
const styleDiv = document.createElement('div');
styleDiv.setAttribute('class', 'style');
const getStyleContainer = document.getElementById('style-container');
getStyleContainer.appendChild(styleDiv);
styleDiv.style.width = ('100px');
styleDiv.style.height = ('200px');
styleDiv.style.margin = ('20px');
styleDiv.style.display = ('flex');
styleDiv.style.justifyContent = ('center');
styleDiv.style.alignItems = ('center');
const styleImage = document.createElement('img');
styleDiv.appendChild(styleImage);
styleImage.innerHTML = styles[i].img;
styleImage.style.width = ('100px');
styleImage.style.height = ('200px');
styleImage.style.objectFit = ('contain');
}
}
window.onload = () => {
createStyle();
}
Any help would be hugely appreciated
Thanks
Solution
InnerHtml property sets or returns the HTML content (inner HTML) of an element. For image use src to set the path
styleImage.innerHTML = styles[i].img; to styleImage.src= styles[i].img;
Answered By - Suresh Answer Checked By - Senaida (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.