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.
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 donew Image(). Keep in mind when you create an element in such a manner, it not yet part of the DOM. You must add it usingappendChildor 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 isdocument.getElementsByTagName("image"), which returns an array you can iterate through.