javascript – Is there a way to dynamically insert an absolutely positioned HTML element in a way that is compatible with IE? – Education Career Blog

Here’s my JavaScript code:

function BuildObject(container, index, imgFile, left, top, width, height)
{
  var newImg = document.createElement('img');
  newImg.setAttribute("id","d" + index);
  newImg.setAttribute("src", imgFile);
  newImg.setAttribute("style", "position:absolute; left:" + left + "px; top:" + top + "px");
  newImg.setAttribute("width", width);
  newImg.setAttribute("height", height);
  container.insertBefore(newImg, container.firstChild);
}

BuildObject(document.body, 1, "pixel.gif", 100, 100, 1, 1);

In Google chrome, this generates the following code as the first element in the body:

<img id="1" src="pixel.gif" style="position:absolute; left:100; top:100; " width="1" height="1">

This works as expected in Google chrome, but not in IE. In IE it creates the element, but positions each element relatively in the top, left corner, next to each other. If I create the tags manually in HTML, IE positions them correctly, but not if I do this with JavaScript.

Any ideas as to how I can do this dynamically so that it works in IE?

,

Instead of setting the “style” attribute like that, do this:

newImg.style.position = 'absolute';
newImg.style.left = left + 'px';

etc. In general using setAttribute() like that is not really correct. Set the properties on the DOM object directly, unless you’re working with non-standard attributes added in the HTML markup.

Leave a Comment