[Javascript] Changing an Objects ID and Name
John Warner
john at jwarner.com
Wed Sep 6 13:34:35 CDT 2006
Paul, let me show my ignorance, but can you 'swap' id attributes in the
fashion below? What I mean is you would seem to have for a moment two
elements with the same ID. The parser 'should' get rather upset with
this situation. Of course I know there is something I'm not seeing here.
John Warner
> -----Original Message-----
> From: javascript-bounces at LaTech.edu
> [mailto:javascript-bounces at LaTech.edu] On Behalf Of Paul Novitski
> Sent: Wednesday, September 06, 2006 11:22 AM
> To: javascript at LaTech.edu
> Subject: Re: [Javascript] Changing an Objects ID and Name
>
>
> 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