[Javascript] Changing an Objects ID and Name

Paul Novitski paul at juniperwebcraft.com
Wed Sep 6 10:21:48 CDT 2006


At 9/6/2006 05:56 AM, Terry Riegel wrote:
>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.
...
>The important thing Is I would like to swap all of the attributes
>out. i.e. width,height,id,name,src


Terry,

What hurdles have you encountered doing exactly what you're wanting 
to do?  Like others on this list, I'm curious to know if there are
other solutions to whatever your problem might be, but I don't see 
why you can't simply do what you want.  Attributes including id are 
read/write.  Swapping them is not difficult.  Once you've pointed to 
an object, e.g.

         var oObj1 = document.getElementById(sId1);

you can change all of its attributes, including id.

Some attributes such as id have named nodes in the DOM:

         sSwapAttribute = oObj1.id;
         oObj1.id = oObj2.id;
         oObj2.id = sSwapAttribute;

http://developer.mozilla.org/en/docs/DOM:element.id

Others need to be access using getAttribute() & setAttribute():

         sSwapAttribute = oObj1.getAttribute("foo");
         oObj1.setAttribute("foo", oObj2.getAttribute("foo"));
         oObj2.setAttribute("foo", sSwapAttribute);

http://developer.mozilla.org/en/docs/DOM:element.getAttribute
http://developer.mozilla.org/en/docs/DOM:element.setAttribute

You can also make good use of attributes() which returns an array of 
all attributes of the specified element.
http://developer.mozilla.org/en/docs/DOM:element.attributes

However, this seems like a lot of logic to accomplish a simpler task, 
to swap the actual nodes in the DOM, as Jonathan points out.

Philosophically, one wonders: if you swap all the attributes of two 
elements, what's left to distinguish them?  Their placement in the 
HTML markup.  Their placement is significant because it determines 
their sequence in the markup structure and because it can affect 
their visual placement on the page.  I would say that in the majority 
of cases one can swap two elements in the visual layout using 
CSS.  If this presentational swapping is your goal, there are 
alternative methods you might consider (such as simply swapping their 
classNames).

Regards,
Paul 




More information about the Javascript mailing list