javascriptimagedomjavascript-objectsdom-manipulation

How to add image in object key value with paragraph in JavaScript object


Basically, the webpage has content in two languages that's why i want to pass image with paragraph from JavaScript object.But it is showing me [object HTMLImageElement] instead of image.

html:

  <p id="ourvisioncardparagraph" >
   // Here the image will appear with paragraph tag
  </p>

js:

var img = new Image();
img.src ="https://images.unsplash.com/photo-1664575198308-3959904fa430?ixlib=rb-4.0.3&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80";
img.alt = "star"

var data = {
  english: {
    ourvisioncardparagraph: `To reinvent finance through innovation & technology ${img} making 
      it convenient, accessible & fair to all.`
}
}

Solution

  • You can use img.outerHTML to get an elements html. So all in all:

    var img = new Image();
    img.src ="https://images.unsplash.com/photo-1664575198308-3959904fa430?ixlib=rb-4.0.3&ixid=MnwxMjA3fDF8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=870&q=80";
    img.alt = "star";
    
    var data = {
      english: {
      ourvisioncardparagraph: `To reinvent finance through innovation & technology ${img.outerHTML} making  it convenient, accessible & fair to all.`
        }
    }
    
    document.getElementById("ourvisioncardparagraph").innerHTML = data.english.ourvisioncardparagraph;