0

I would like to ask if there is a more elegant way to insert images to html with javascript without jQuery than:

<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title></title> </head> <body> <script> for(i = 0; i < 3; i++) { name = i + "_img"; document.write("<img name=" + name + " />"); img = document.images[name]; img.src = i + ".png"; } </script> </body> </html> 

Eventually I am gonna have there much more atributes and I want to avoid using < img /> as much as possible to make it more transparent.

1 Answer 1

3

You can create elements in JavaScript by using document.createElement("tag"). For example, document.createElement("image"). So you don't need to construct a string like you're doing. For some elements, such as an image, you can also just do new Image(). Keep in mind when you create an element in such a manner, it not yet part of the DOM. You must add it using appendChild or some other means.

Also, I would refrain from using document.images[] as I'm not sure that's entirely cross-browser friendly. I believe the standard practice is document.getElementsByTagName("image"), which returns an array you can iterate through.

var whereToAppend = document.getElementsByTagName("body")[0]; for(var i = 0; i < 3; i++) { var name = i + "_img"; var img = new Image(); img.src = i + ".png"; whereToAppend.appendChild(img); } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.