Adding Images to an HTML Document with JavaScript

Adding images to an HTML document with JavaScript

You need to use document.getElementById() in line 3.

If you try this right now in the console:

var img = document.createElement("img");img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";var src = document.getElementById("header");src.appendChild(img);
<div id="header"></div>

How do I insert an image into HTML with Javascript

Update

OP needs a way to style images. See Demo 3


The function was missing:

  1. A target element to place the img
    • Added a <figure> to the layout
    • Reference target: var frame = document.querySelector('.frame');
  2. Once an element is created, it must be added to the DOM

    • frame.appendChild(ilona);

See Demo 1


An alternative way to adding an image programmatically to the DOM is by using a method or property that takes a given string and parses it into HTML like innerHTML or insertAdjacentHTML(). Demo 2 uses insertAdjacentHTML() and Template Literal.


Demo 1

<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8"> <title>PingPongKép</title>
</head>
<body>
<figure class='frame'> <figcaption>Image 1</figcaption> </figure>

<script> function ilonaKep() { var frame = document.querySelector('.frame'); var ilona = document.createElement("IMG"); ilona.src = "http://p1.vatera.hu/photos/52/52/b859_4_big.jpg?v2"; ilona.width = "300"; frame.appendChild(ilona); }
ilonaKep() </script></body>
</html>

How to insert an image with Javascript?

Fixed HTML (switched classes and IDs to make IDs unique) and added an image ID for simplicity:

<div id="msgStyle1" class="message">Waiting for image</div>
<div id="imgStyle1" class="message">
<img src="" id="image" />
</div>

JS:

document.getElementById('image').src = 'http://yourImagePathHere';

See it work here: http://jsfiddle.net/N3rCm/

add an image to a product with Javascript

well I have tried this on my machine and it works fine!!,

My HTML CODE

<html>
<head>
<title> Image </title>
<script src="./index.js" defer></script>
</head>
<body>
<button class="btn"> Add Image </button>
<img id="image">
</body>
</html>

My JS Code

document.querySelector(".btn").addEventListener("click", () => {
const path = "./img/Screenshot (1).png";
const img = document.querySelector("#image");
img.src = path;
});

add image as div with javascript

You can use this script

count = 0;function viewImage(){var imagefile = document.querySelector('#image');                if (imagefile.files && imagefile.files[0]) {                    var reader = new FileReader();                    reader.onload = function (e) {var content = '<img id="temp_image_'+count+'" style="border: 1px solid; width: 107px;height:107px;" >';document.querySelector('#all_images').innerHTML += content;document.querySelector('#temp_image_'+count).setAttribute('src', e.target.result);                    };  reader.readAsDataURL(imagefile.files[0]);                  this.imagefile = imagefile.files[0];                  count++;                }else{                    console.log("Image not selected");                }   }
<div id="all_images"></div><input id="image" name="image" type="file" onChange="viewImage()">

How to insert image in table

It should work this way, not tested though (and I smashed some other bugs in your function):

function add(form) {
table1 = document.getElementById('mytable');
row1 = table1.insertRow(table1.rows.length);
cell1 = row1.insertCell(row1.cells.length);
cell1 = row1.rowIndex;
cell2 = row1.insertCell(row1.cells.length);
let file = document.getElementsByName('pic')[0].files[0];
let src = URL.createObjectURL(file);
let image = document.createElement('img');
image.src = src;
cell2.appendChild(image);
// ...
}

Reference: https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL

How can I render Images with JavaScript into my HTML

The problem is that you use an equal sign (=) rather than a plus-equal sign (+=). The plus-equal sign will add the text to the variable, while the equal sign will overwrite the variable.

This line:

        getImgs = `<img scr="${imgs[i]}">`

getImgs is being set to the string, the string is not being added to it. You need to change it to something like this:

        getImgs += `<img scr="${imgs[i]}">`

(Notice the plus before the equal sign)

This way, the variable will not be completely changed, rather it will be appended to.

Full code:

const imgs = [
"images/p1.jpg",
"images/p2.jpg",
"images/p3.jpg"
]

const container = document.getElementById("container")

function renderImages() {
let getImgs = ""
for (let i = 0; i < imgs.length; i++) {
getImgs += `<img scr="${imgs[i]}">`
}
container.innerHTML = getImgs
}

renderImages()
/* I added css so you can see the images */
img {
border: 1px solid black;
width: 20px;
height: 20px;
background: linear-gradient(90deg, blue, green);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Headline</h1>
<div id="container">

</div>
</body>
</html>

Is it possible to insert an image without using a filepath src?

Yes, see FileReader.readAsDataURL(): read file as data URI.

document.getElementById("input1").onchange = function(e) {  var someImage = e.target.files[0]  var reader = new FileReader();  var img = document.getElementById('preview');  reader.onload=function(){    img.src = reader.result  }  reader.readAsDataURL(someImage)}
<input type="file" id="input1" accept="image/*" /><img id="preview" src="" />


Related Topics



Leave a reply



Submit