[javascript] What is the best JavaScript code to create an img element

I want to create a simple bit of JS code that creates an image element in the background and doesn't display anything. The image element will call a tracking URL (such as Omniture) and needs to be simple and robust and work in IE 6 =< only. Here is the code I have:

var oImg = document.createElement("img");
oImg.setAttribute('src', 'http://www.testtrackinglink.com');
oImg.setAttribute('alt', 'na');
oImg.setAttribute('height', '1px');
oImg.setAttribute('width', '1px');
document.body.appendChild(oImg);

Is this the simplest but most robust (error free) way to do it?

I cannot use a framework like jQuery. It needs to be in plain JavaScript.

This question is related to javascript dhtml

The answer is


This is the method I follow to create a loop of img tags or a single tag as ur wish

method1 :
    let pics=document.getElementById("pics-thumbs");
            let divholder=document.createDocumentFragment();
            for(let i=1;i<73;i++)
            {
                let img=document.createElement("img");
                img.class="img-responsive";
                img.src=`images/fun${i}.jpg`;
                divholder.appendChild(img);
            }
            pics.appendChild(divholder);

or

method2: 
let pics = document.getElementById("pics-thumbs"),
  imgArr = [];
for (let i = 1; i < 73; i++) {

  imgArr.push(`<img class="img-responsive" src="images/fun${i}.jpg">`);
}
pics.innerHTML = imgArr.join('<br>')
<div id="pics-thumbs"></div>

Are you allowed to use a framework? jQuery and Prototype make this sort of thing pretty easy. Here's a sample in Prototype:

var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem);

jQuery:

$('#container').append('<img src="/path/to/image.jpg"
       width="16" height="16" alt="Test Image" title="Test Image" />');

I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):

$('#container').append($('<img>', { 
    src : "/path/to/image.jpg", 
    width : 16, 
    height : 16, 
    alt : "Test Image", 
    title : "Test Image"
}));

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).


var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Just to add full html JS example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>create image demo</title>
    <script>


        function createImage() {
            var x = document.createElement("IMG");
            x.setAttribute("src", "http://www.iseebug.com/wp-content/uploads/2016/09/c2.png");
            x.setAttribute("height", "200");
            x.setAttribute("width", "400");
            x.setAttribute("alt", "suppp");
            document.getElementById("res").appendChild(x);
        }

    </script>
</head>
<body>
<button onclick="createImage()">ok</button>
<div id="res"></div>

</body>
</html>

This is the method I follow to create a loop of img tags or a single tag as ur wish

method1 :
    let pics=document.getElementById("pics-thumbs");
            let divholder=document.createDocumentFragment();
            for(let i=1;i<73;i++)
            {
                let img=document.createElement("img");
                img.class="img-responsive";
                img.src=`images/fun${i}.jpg`;
                divholder.appendChild(img);
            }
            pics.appendChild(divholder);

or

method2: 
let pics = document.getElementById("pics-thumbs"),
  imgArr = [];
for (let i = 1; i < 73; i++) {

  imgArr.push(`<img class="img-responsive" src="images/fun${i}.jpg">`);
}
pics.innerHTML = imgArr.join('<br>')
<div id="pics-thumbs"></div>

Shortest way:

(new Image()).src = "http:/track.me/image.gif";

var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Shortest way:

(new Image()).src = "http:/track.me/image.gif";

jQuery:

$('#container').append('<img src="/path/to/image.jpg"
       width="16" height="16" alt="Test Image" title="Test Image" />');

I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):

$('#container').append($('<img>', { 
    src : "/path/to/image.jpg", 
    width : 16, 
    height : 16, 
    alt : "Test Image", 
    title : "Test Image"
}));

As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).


Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...

document.getElementById("image-holder").innerHTML = "<img src='image.png' alt='The Image' />";

By the way, innerHTML is not that bad


Shortest way:

(new Image()).src = "http:/track.me/image.gif";

Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...

document.getElementById("image-holder").innerHTML = "<img src='image.png' alt='The Image' />";

By the way, innerHTML is not that bad


you could simply do:

var newImage = new Image();
newImage.src = "someImg.jpg";

if(document.images)
{
  document.images.yourImageElementName.src = newImage.src;
}

Simple :)


As others pointed out if you are allowed to use a framework like jQuery the best thing to do is use it, as it high likely will do it in the best possible way. If you are not allowed to use a framework then I guess manipulating the DOM is the best way to do it (and in my opinion, the right way to do it).


var img = new Image(1,1); // width, height values are optional params 
img.src = 'http://www.testtrackinglink.com';

jQuery:

$('#container').append('<img src="/path/to/image.jpg"
       width="16" height="16" alt="Test Image" title="Test Image" />');

I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):

$('#container').append($('<img>', { 
    src : "/path/to/image.jpg", 
    width : 16, 
    height : 16, 
    alt : "Test Image", 
    title : "Test Image"
}));

var img = new Image(1,1); // width, height values are optional params 
img.src = 'http://www.testtrackinglink.com';

Are you allowed to use a framework? jQuery and Prototype make this sort of thing pretty easy. Here's a sample in Prototype:

var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem);

Just for the sake of completeness, I would suggest using the InnerHTML way as well - even though I would not call it the best way...

document.getElementById("image-holder").innerHTML = "<img src='image.png' alt='The Image' />";

By the way, innerHTML is not that bad


var img = document.createElement('img');
img.src = 'my_image.jpg';
document.getElementById('container').appendChild(img);

Just to add full html JS example

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>create image demo</title>
    <script>


        function createImage() {
            var x = document.createElement("IMG");
            x.setAttribute("src", "http://www.iseebug.com/wp-content/uploads/2016/09/c2.png");
            x.setAttribute("height", "200");
            x.setAttribute("width", "400");
            x.setAttribute("alt", "suppp");
            document.getElementById("res").appendChild(x);
        }

    </script>
</head>
<body>
<button onclick="createImage()">ok</button>
<div id="res"></div>

</body>
</html>

Are you allowed to use a framework? jQuery and Prototype make this sort of thing pretty easy. Here's a sample in Prototype:

var elem = new Element('img', { 'class': 'foo', src: 'pic.jpg', alt: 'alternate text' });
$(document).insert(elem);