Insert image into table cell in Javascript

I want to paste images into a newly created cell. How can I do it? Can someone help me with this? Here is my code for insertcells:

<!DOCTYPE html> <html> <head> <script> function displayResult() { var firstRow=document.getElementById("myTable").rows[0]; var x=firstRow.insertCell(-1); x.innerHTML="New cell" } </script> </head> <body> <table id="myTable" border="1"> <tr> <td>First cell</td> <td>Second cell</td> <td>Third cell</td> </tr> </table> <br> <button type="button" onclick="displayResult()">Insert cell</button> </body> </html> 

All I want to do is paste the image into the created cell.

+6
source share
3 answers

You can create an image element and add it to a new cell:

 function displayResult() { var firstRow=document.getElementById("myTable").rows[0]; var x=firstRow.insertCell(-1); x.innerHTML="New cell"; var img = document.createElement('img'); img.src = "link to image here"; x.appendChild(img); } 

Beware of creating raw HTML for the image, if you do, you need to make sure that you avoid src and any other attributes.

+12
source

Just set the inner HTML of the new cell to the img HTML element with any src or attributes you want.

 function displayResult() { var firstRow=document.getElementById("myTable").rows[0]; var x=firstRow.insertCell(-1); x.innerHTML="<img src='myImageURL' alt='hello'/>"; } 
+4
source
  function displayResult() { document.getElementById("myTable").rows[0].innerHTML="your image"; } 

maybe it can help, dynamism can be achieved later, just try if it works now?

0
source

Source: https://habr.com/ru/post/946747/