[Javascript] Changing an Objects ID and Name

Jonathan Buchanan jonathan.buchanan at gmail.com
Wed Sep 6 09:20:27 CDT 2006


On 9/6/06, Terry Riegel <riegel at clearimageonline.com> wrote:
> Hello,
>
> I would like to swap out an image in an application I am writing.
> Basically I want to swap two image tags, the trick is I want to swap
> their ID and NAME tags also.
>
> For example, I have the following HTML...
>
>
>   ...
> <img src="image1.jpg" width="100" height="200" name="abc" id="abc">
>   ...
> <img src="image2.jpg" width="120" height="180" name="def" id="def">
>   ...
>
>
> that I would like to use javacscript to make into...
>
>   ...
> <img src="image2.jpg" width="120" height="180" name="def" id="def">
>   ...
> <img src="image1.jpg" width="100" height="200" name="abc" id="abc">
>   ...
>
> The important thing Is I would like to swap all of the attributes
> out. i.e. width,height,id,name,src
>
> Thanks,
>
> Terry Riegel

If you want to swap element locations (which is what you're really
doing, if I've understood the question correctly), do it directly
using the DOM instead of fiddling about with element attributes:

function swapNodes(n1, n2)
{
    var placeHolder = document.createElement("span");
    n1.parentNode.replaceChild(placeHolder, n1);
    n2.parentNode.replaceChild(n1, n2);
    placeHolder.parentNode.replaceChild(n2, placeHolder);
}

swapNodes(document.getElementById("abc"), document.getElementById("def"));

Regards,
Jonathan.



More information about the Javascript mailing list