Adding an img element to a div with javascript - javascript

I am trying to add an img to the placehere div using JavaScript, however I am having no luck. Can anyone give me a hand with my code?
<html>
<script type="text/javascript">
var elem = document.createElement("img");
elem.setAttribute("src", "images/hydrangeas.jpg");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild("elem");
</script>
<body>
<div id="placehere">
</div>
</body>
</html>

document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';

It should be:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
window.onload = function() {
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
<div id="placehere"></div>
To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.

function image()
{
//dynamically add an image and set its attribute
var img=document.createElement("img");
img.src="p1.jpg"
img.id="picture"
var foo = document.getElementById("fooBar");
foo.appendChild(img);
}
<span id="fooBar"> </span>

The following solution seems to be a much shorter version for that:
<div id="imageDiv"></div>
In Javascript:
document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';

In case anyone is wondering how to do it with JQuery:
$("<img height='200' width='200' alt='testImage' src='https://avatars.githubusercontent.com/u/47340995?v=4'> </img>").appendTo("#container");
Ref: https://api.jquery.com/jQuery/#jQuery2

Related

How to insert <img> tag, or JS script through textContent? [duplicate]

I've tried some HTML DOM code from several sites, but it isn't working. It isn't adding anything. Does anyone have a working example on this?
this.img = document.createElement("img");
this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = getElementById("gamediv");
src.appendChild(this.img)
But it isn't adding anything to the div gamediv. I've tried document.body as well, with no result.
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>
... you'd get this:
With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As JavaScript reads down a page).
<head>
<script type="text/javascript">
function insert(){
var src = document.getElementById("gamediv");
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src.appendChild(img);
}
</script>
</head>
<body>
<div id="gamediv">
<script type="text/javascript">
insert();
</script>
</div>
</body>
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
Use Image() instead
Instead of using document.createElement() use new Image()
const myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').
or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>
Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)
Things to ponder:
Use jquery
Which this is your code refering to
Isnt getElementById usually document.getElementById?
If the image is not found, are you sure your browser would tell you?

I am trying to add an image to HTML using javascript but there is no content?

When I try to add the Image with javascript, it displays the boarder of the image but there is no content inside. It is just an empty blank box. Any ideas?
Javascript:
var img=document.createElement("img");
img.src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
var src = document.getElementById("gameboard");
src.appendChild(img);
HTML:
<body>
<div>
<img id="gameboard">
</div>
</body>
Jsfiddle:
https://jsfiddle.net/bj5d6t7k/1/
You are trying to append image inside another image which is not allowed. Simply set the src attribute of the existing image:
var img=document.getElementById("gameboard");
img.src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
<body>
<div>
<img id="gameboard">
</div>
</body>
OR: If you want to create the element and append that with Node.appendChild()
The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.
var img=document.createElement("img");
img.src="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
var gamecontiner = document.getElementById("gamecontiner");
gamecontiner.appendChild(img);
<body>
<div id="gamecontiner">
</div>
</body>
Please check this below code
var img = new Image();
var div = document.getElementById('gameboard');
img.onload = function() {
div.appendChild(img);
};
img.src = 'path/to/image.jpg'
As per your code you are appending one image above another one
After load document then access node.
Give id to div tag.
See below,
<script>
document.addEventListener("DOMContentLoaded", function (event) {
var img = document.createElement("img");
img.src = "https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500";
var srcimg = document.getElementById("gameboard");
srcimg.appendChild(img);
});
</script>
<body>
<div id="gameboard">
</div>
</body>

how to append a div between two anchor elements

i have got two anchor elements:
<a onclick="PostMenuAction('abc');" class="port" title="AddPort" id="lnkPort">port</a>
and
<a onclick="PostMenuAction('def');" class="crop" title="AddCrop" id="lnkCrop">crop</a>
Now i want a div with a small image to be inserted between the two.
so it will be
<a onclick="PostMenuAction('abc');" class="port" title="AddPort" id="lnkPort">port</a>
<div id="additionaldiv"> <img src="" id="additional img" /> </div>
<a onclick="PostMenuAction('def');" class="crop" title="AddCrop" id="lnkCrop">crop</a>
Can you please help me out adding the same?
my pleasure if this solved using javascript
Thanks in advance
Here you go. You can make this into a JavaScript Function:
var div = document.createElement("div");
var img = document.createElement("img");
img.src = "/path/to/image";
div.appendChild(img);
var a = document.getElementById("lnkCrop");
a.parentNode.insertBefore(div,a);
Here's a JavaScript function to do it:
function addImageBefore(path, id) {
var div = document.createElement('div'),
img = document.createElement('img'),
refElement = document.getElementById(id);
if (!refElement) {// Presumably atypical, hence not worrying about creating above
return null;
}
img.src = path;
div.appendChild(img);
refElement.parentNode.insertBefore(div, refElement);
return div;
}
Call it in your case like this:
addImageBefore("path/to/img", "lnkCrop");
Put that call in whatever event handler or what-have-you you want to trigger the addition with.
More in the DOM specs: DOM2 Core, DOM2 HTML, DOM3 Core.
Here you go:
<a onclick="PostMenuAction('abc');" class="port" title="AddPort" id="lnkPort">port</a>
<div><img src="small.gif" alt="" /></div>
<a onclick="PostMenuAction('def');" class="crop" title="AddCrop" id="lnkCrop">crop</a>
You can call a javascript to do this. Below is the way to do this feature.
document.getElementById("lnkPort").innerHTML = document.getElementById("lnkPort").innerHTML+'<div><h1>Test</h1></div>';

JavaScript images

How do I display the same image on the same page multiple times?
<head>
<Script language="javascript">
function xdf(){
for (i=0;i<10;i++) {
document.write('<b>hello world</b><br>');
}
}
</script>
</head>
this code displays "hello world" 10 times.
i would like the same thing but with certain image instead of "hello word"...
You can use document.createElement() to create an img element in JavaScript, and Node.appendChild() to append it to some other node:
var img = document.createElement('img');
img.setAttribute('src', 'my_image.png');
document.getElemenetById('some-div').appendChild(img);
The image will be loaded from the browser's cache if the above is repeated multiple times, appending each new img element to multiple nodes.
As #Matthew Flaschen suggested in a comment below, you could also use the Node.cloneNode() solution instead. You can create your img elment once:
var img = document.createElement('img');
img.setAttribute('src', 'my_image.png');
... and then use img.cloneNode(false) as an argument for appendChild():
document.getElemenetById('some-div').appendChild(img.cloneNode(false));
document.getElemenetById('some-other-div').appendChild(img.cloneNode(false));
<img src="/path/to/img.png"/> <img src="/path/to/img.png"/>
you can clone the images:
<div><img src="http://www.google.com/favicon.ico" id="image" /></div>
<script type="text/javascript">
n = 5;
img = document.getElementById("image");
for (i=0; i<n-1; i++) {
img2 = img.cloneNode(false);
img2.id = img.id + "_clone" + i;
img.parentNode.appendChild(img2);
}
</script>
.. or maybe you'd rather want to define the background, using CSS?
<style type="text/css">
body { background: url("http://www.google.com/favicon.ico") left repeat-y; }
</style>
(assuming from your previous comment, that you want to have the images in one column on the left edge)
Change:
document.write('<b>hello world</b><br>');
Into:
document.write('<img src="IMAGE FILE NAME HERE.png" alt="TEXT HERE"><br>');

Adding images to an HTML document with JavaScript

I've tried some HTML DOM code from several sites, but it isn't working. It isn't adding anything. Does anyone have a working example on this?
this.img = document.createElement("img");
this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = getElementById("gamediv");
src.appendChild(this.img)
But it isn't adding anything to the div gamediv. I've tried document.body as well, with no result.
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>
... you'd get this:
With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As JavaScript reads down a page).
<head>
<script type="text/javascript">
function insert(){
var src = document.getElementById("gamediv");
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src.appendChild(img);
}
</script>
</head>
<body>
<div id="gamediv">
<script type="text/javascript">
insert();
</script>
</div>
</body>
This works:
var img = document.createElement('img');
img.src = 'img/eqp/' + this.apparel + '/' + this.facing + '_idle.png';
document.getElementById('gamediv').appendChild(img)
Or using jQuery:
$('<img/>')
.attr('src','img/eqp/' + this.apparel + '/' + this.facing + '_idle.png')
.appendTo('#gamediv');
Use Image() instead
Instead of using document.createElement() use new Image()
const myImage = new Image(100, 200);
myImage.src = 'picture.jpg';
document.body.appendChild(myImage);
https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/Image
The Image() constructor creates a new HTMLImageElement instance. It is functionally equivalent to document.createElement('img').
or you can just
<script>
document.write('<img src="/*picture_location_(you can just copy the picture and paste it into the script)*\"')
document.getElementById('pic')
</script>
<div id="pic">
</div>
Get rid of the this statements too
var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)
Things to ponder:
Use jquery
Which this is your code refering to
Isnt getElementById usually document.getElementById?
If the image is not found, are you sure your browser would tell you?

Categories