10emil10 10emil10 - 2 months ago 7
Javascript Question

Pictures in JavaScript

I am working on a project in JavaScript. And I was wondering if there is a way to display an image, without using HTML. I am new to JavaScript. I do not mind links to pages I need to read. I just cannot find a place, which answers this question.

I simple wish to display it in a web browser, so all I need is a line of code which would replace this code in html:

<img src="my/string.jpg" alt="Mountain View" style="width:1210px;height:688px">

Answer

I simple wish to display it in a web browser, so all I need is a line of code which would replace this code in html:

<img src="my/string.jpg" alt="Mountain View" style="width:1210px;height:688px">

You can do that with the DOM: You'd use createElement and appendChild or insertBefore:

var img = document.createElement('img');
img.src = "my/string.jpg";
img.alt = "Mountain View";
img.style.width = "1210px";
img.style.height = "688px";
document.body.appendChild(img); // Or wherever you want to put it

If you don't mind using HTML but just want to do it under programmatic control, you can use the insertAdjacentHTML method or the innerHTML property:

document.body.insertAdjacentHTML(
    'beforeend',
    '<img src="my/string.jpg" alt="Mountain View" style="width:1210px;height:688px">'
);

...or

someElement.innerHTML = '<img src="my/string.jpg" alt="Mountain View" style="width:1210px;height:688px">';