Home > database >  Can I add image tag inside of a string in Javascript <script> tag?
Can I add image tag inside of a string in Javascript <script> tag?

Time:06-04

I have a javascript function that I use to insert generated content into a <div> element in my HTML page like this :

document.getElementById('testID').innerHTML = addToTable(object)

However, the images are not appearing and I cannot figure out why this is the case. Is there a different way to approach adding images when doing it like this as a string inside of a script tag?

The image paths are correct and show up when I hardcode them directly into the HTML.

<script>
    function addToTable(object) {
        var html = "";

        for (let i= 0; i< object.Total; i  ) {

            if (object[i].Condition == "Normal") {

                html  = "<div class='tablet'>"  
                    "<div class='test'>"  
                    "<a href='#'><img src='~/Images/test1.svg'></a>"  
                    "<a href='#'><img src='~/Images/test2.svg'></a>"  
                    "</div>"  
                    "</div>";
            }
        }
        return html;
    };

</script>

CodePudding user response:

You can use template literals to write your string across multiple lines instead of doing concatenation. This will let you use double quotes for your attributes and generally make the code more readable.

html  = `
  <div >
    <div >
      <a href="#"><img src="~/Images/test1.svg"></a>
      <a href="#"><img src="~/Images/test2.svg"></a>
    </div>
  </div>
`;

If that doesn't help, the problem is likely related to your input.

Either :

  • object.Total is always <= 0

Or :

  • object[i].Condition == "Normal" is never true

But since you haven't provided a sample of your input data it's not possible to tell for sure.

CodePudding user response:

looks like your code is fine. check the path to your images

let html = "<div class='tablet'>"  
                    "<div class='test'>"  
                    "<a href='#'><img src='https://via.placeholder.com/100x150'></a>"                     
                    "</div>"  
                    "</div>";
                    
                    
document.getElementById('test').innerHTML = html
<div id='test'></div>

  • Related