Home > Net >  How to properly add img element with innerHTML
How to properly add img element with innerHTML

Time:10-29

I'm trying to render some img elements with innerHTML, in some cases it works and in others it doesn't.

In this example I joined two images into a single string and one renders correctly and the other does not.

Maybe it's a encoding issue? Is there any way to escape the string to solve the problem?

these strings are returned from the database

const html = '<p>First Image:</p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150px" height="150px"/> <p>Second Image: </p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150px" height="150px"/>';


const div = document.getElementById("div-test");
div.innerHTML = html;

console.log("innerHTML: ", div.innerHTML);
<div id="div-test" />
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

I think its placehold.it domain issue. It's not loading properly in innerHTML but when I use an image from via.placeholder.com it's working fine.

const html = '<img src="https://via.placeholder.com/350x150"/>';


const div = document.getElementById("div-test");
div.innerHTML = html;

console.log("innerHTML: ", div.innerHTML);
<div id="div-test"/>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Your code works, but i believe it sometimes shows up and other times it doesnt due to https vs http. Browser will block an image if its not using same protocol as the site running it.

const html = '<p>First Image:</p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150" height="150"/> <p>Second Image: </p> <img src="https://images.pexels.com/photos/8971740/pexels-photo-8971740.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="Test" width="150" height="150"/>';


const div = document.getElementById("div-test");
div.innerHTML = html;

//console.log("innerHTML: ", div.innerHTML);
<div id="div-test" />
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related