Add image elements in DOM using Javascript -
i have image files in folder named imagefolder. file names in form of number_of_suit.png (eg 7_of_diamond.png) , want add them html body. think have syntax issues. example in vanilla js..
var addimage = document.getelementsbytagname("body"); addimage.appendchild(img src = "imagefolder/ + number + "_of_" + suit.png");
thank you.
the basics
you've got couple of issues. start, document.getelementsbytagname
returns nodelist
, not node
there no appendchild
element. around that, either first item of collection, or document.body
:
var addimage = document.getelementsbytagname("body"); // nodelist var bodyone = addimage[0]; // <body> element var bodytwo = document.body; // <body> element
secondly, if see syntax highlighting in example, can see you're missing couple of quotation marks.
var string = "imagefolder/" + number + "_of_" + suit + ".png";
finally, gottz has pointed out, can't reference img src
are. need create img
element , set src
property.
var img = document.createelement("img"); img.src = string;
more advanced
you may have handled this, have small amount of code at, in-case: need wait until dom has finished loading before attempt modify it. best done waiting domcontentloaded
event fire.
document.addeventlistener("domcontentloaded", function () { // work here. });
since you're going creating 52 elements, more efficient create documentfragment
, append new elements that, appending fragment body afterwards. causes fewer re-paints in browser faster.
var fragment = document.createdocumentfragment(); // ... fragment.appendchild(img); // ... document.body.appendchild(fragment);
summing up
the whole thing means code this:
document.addeventlistener("domcontentloaded", function () { "use strict"; var numbers = [2, 3, 4, 5, 6, 7, 8, 9, 10, "jack", "queen", "king", "ace"]; var suits = ["clubs", "diamonds", "hearts", "spades"]; var fragment = document.createdocumentfragment(); suits.foreach(function (suit) { numbers.foreach(function (number) { var img = document.createelement("img"); img.src = "imagefolder/" + number + "_of_" + suit + ".png"; fragment.appendchild(img); }); }); document.body.appendchild(fragment); });
i hope helps.
Comments
Post a Comment