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
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).
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);
you could simply do:
var newImage = new Image();
newImage.src = "someImg.jpg";
if(document.images)
{
document.images.yourImageElementName.src = newImage.src;
}
Simple :)
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
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>