views:

46

answers:

4

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.

+2  A: 

You need to use document.getElementById() in line 3.

If you try this right now in the Firebug 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);

... you'd get this:

Adding images to the HTML with JavaScript

Daniel Vassallo
this.img = document.createElement("img"); this.img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png"; src = document.getElementById("gamediv"); src.appendChild(this.img);Changed it now, but it still doesn't pop up in the div gamediv.
Anonymous
@klausbyskov: Thanks for fixing the typo.
Daniel Vassallo
@Anonymous: Could it be that the `src` path is incorrect? Can you try an image with an absolute path, that you know for sure exists? Such as: `http://www.google.com/intl/en_com/images/logo_plain.png`
Daniel Vassallo
Running the code it says src is null. But I am sure I made a div with gamediv as an id.<div id="gamediv"></div>
Anonymous
I know the src is correct, the comment above is what firebug tells me when I select break on error
Anonymous
@Anonymous: You may want to update the question with this info. It may help you get more answers.
Daniel Vassallo
A: 

Things to ponder:

  1. Use jquery
  2. Which this is your code refering to
  3. Isnt getElementById usually document.getElementById?
  4. If the image is not found, are you sure your browser would tell you?
Kristoffer S Hansen
A: 

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)
Peter Bridger
Why? It's in a class.
Anonymous
A: 

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');
Guffa