Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

Thanks in advance.

like image 259
Anonymous Avatar asked Apr 29 '10 08:04

Anonymous


People also ask

How do I put an image in HTML in HTML?

The HTML <img> tag is used to embed an image in a web page. Images are not technically inserted into a web page; images are linked to web pages. The <img> tag creates a holding space for the referenced image. The <img> tag is empty, it contains attributes only, and does not have a closing tag.

How can we include images in a web page using HTML and JavaScript?

How do we put an image on a webpage? In order to put a simple image on a webpage, we use the <img> element. This is an empty element (meaning that it has no text content or closing tag) that requires a minimum of one attribute to be useful — src (sometimes spoken as its full title, source).


2 Answers

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:

enter image description here

like image 78
Daniel Vassallo Avatar answered Sep 26 '22 01:09

Daniel Vassallo


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> 
like image 31
user2886138 Avatar answered Sep 24 '22 01:09

user2886138