开发者

DOM appendChild alternate

I am creating a DOM element as follows;

var imgEle = document.createElement('img');
    imgEle.src = imgURL;         
    x.appendChild(imgEle);

Now for the last line instead of appending which creates multiple img elements each time the function is called, I want it to be replaced OR always be the first child elemen开发者_JAVA技巧t of x..

How should i do the same for crossbrowser compatibility?


var xChildren = x.childNodes;
if(xChildren[0])
   x.replaceChild(myIMG, xChildren[0]);
else
   x.appendChild(myIMG);

that should do the trick

We are grabbing all the child Elements of X, and then we check to see if the first of them is Defined. (If there are more than one you can also use the x.innerHTML method to remove them all at once). If it is defined we replace it with our newly created element, if it is not - we simply append the element.

EDIT: By creating and appending elements in a loop, you 're making your script a bit heavy - since it seems that you want to just change the image contained within x, why don't you simply resort to chaning the .src attribute?

var xChildren = x.childNodes;
var myIMG;    
if(xChildren[0])
   mIMG = xChildren[0]; //you should be sure that this is an image 
   // perhaps you might want to check its type.
else{
   mIMG = document.createElement("img");
   mIMG.src = "source";
   x.appendChild(mIMG);
}

//now the loop
while( your_condition )
    mIMG.src = "source of the image";

This way, you 're only using and editing one element.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜