473,396 Members | 2,052 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Swap DOM objects in / out to object variables?

I know its possible to dynamically remove elements from the DOM, but
rather than deleting them forever, is it possible to 'capture' them and
save them as an object variable so they can be reused elsewhere?

Consider this...

There are 2 DIV tags with the same ID value.

Wouldn't it be a neat trick if you could move one of the DIV tags out
to an object variable so that a getElementById() would return a result
for DIV tag that remained? Swapping the first DIV tag object back and
repeating the process on the second would return the first DIV tag on a
getElementById().

I tried cloning a DOM element by creating a clone() prototype function
on the Object object, but that didn't work.

Any ideas anyone?

Steve

Jul 23 '05 #1
13 2987
I don't guarantee this for standards or cross-browser compatibility, but
on latest IE it works:
<head>
<title>
Test of Div Replacement using Cloning and removeNode will swap the divs
three times thus leaving them in reverse order
</title>
<script>
function swapem() {
var mydiv=document.getElementById("my1").cloneNode(tru e);
document.getElementById("my1").removeNode(true);
alert(document.getElementById("my1").innerHTML);
document.getElementById("my1").insertAdjacentEleme nt("afterEnd",mydiv);
}
</script>
</head>
<body
onload="alert(document.getElementById('my1').inner HTML);swapem();swapem();swapem();">
<DIV id=my1>
This is div1
</div>
<div id=my1>
This is div1.1
</div>
</body>
Jul 23 '05 #2
On 26 Jan 2005 19:08:29 -0800, in comp.lang.javascript
sn****@mxlogic.com wrote:
| I know its possible to dynamically remove elements from the DOM, but
| rather than deleting them forever, is it possible to 'capture' them and
| save them as an object variable so they can be reused elsewhere?
|
| Consider this...
|
| There are 2 DIV tags with the same ID value.
|
| Wouldn't it be a neat trick if you could move one of the DIV tags out
| to an object variable so that a getElementById() would return a result
| for DIV tag that remained? Swapping the first DIV tag object back and
| repeating the process on the second would return the first DIV tag on a
| getElementById().
|
| I tried cloning a DOM element by creating a clone() prototype function
| on the Object object, but that didn't work.
|
| Any ideas anyone?


The fact that you have 2 IDs the same is going to cause the
application logic problems. When you tell the program to manipulate
the ID which ID is it supposed to manipulate, the first or the second?
How will the application 'know' which of the 2 identical IDs are
active or which one to clone?

You'd be better off giving the DIVs unique IDs and NAME attributes.
Then in your code store the 'active' element within a variable and
then do further processing.
---------------------------------------------------------------
jn******@yourpantsyahoo.com.au : Remove your pants to reply
---------------------------------------------------------------
Jul 23 '05 #3


sn****@mxlogic.com wrote:
I know its possible to dynamically remove elements from the DOM, but
rather than deleting them forever, is it possible to 'capture' them and
save them as an object variable so they can be reused elsewhere?
Sure, a node can be detached from the document and stored in a variable
or attached to a document fragment and later on reinserted or moved
elsewhere.

I tried cloning a DOM element by creating a clone() prototype function
on the Object object, but that didn't work.


DOM nodes are host objects so a method on the Object prototype doesn't
help but you can call cloneNode(true) for a deep clone and
cloneNode(false) for a shallow clone on DOM nodes.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #4
Martin,
RE my example above (which only works in IE) can you tell me how I
would convert it to be standards compliant? W3C doesn't appear to
define a removeNode(), only removeChild(), but I got bogged down once I
reached that point, trying to point a document.removeChild to the right
element, and just settled for the IE way.
In article <41*********************@newsread2.arcor-online.net>,
ma*******@yahoo.de says...


sn****@mxlogic.com wrote:
I know its possible to dynamically remove elements from the DOM, but
rather than deleting them forever, is it possible to 'capture' them and
save them as an object variable so they can be reused elsewhere?


Sure, a node can be detached from the document and stored in a variable
or attached to a document fragment and later on reinserted or moved
elsewhere.

I tried cloning a DOM element by creating a clone() prototype function
on the Object object, but that didn't work.


DOM nodes are host objects so a method on the Object prototype doesn't
help but you can call cloneNode(true) for a deep clone and
cloneNode(false) for a shallow clone on DOM nodes.

Jul 23 '05 #5


John Doe wrote:
my example above (which only works in IE) can you tell me how I
would convert it to be standards compliant? W3C doesn't appear to
define a removeNode(), only removeChild(), but I got bogged down once I
reached that point, trying to point a document.removeChild to the right
element, and just settled for the IE way.


Your example seems to start with two elements in one document with the
same id attribute value and what happens with document.getElementById is
left open.
As for removing a node in the W3C DOM
if (node.parentNode) {
node.parentNode.removeChild(node);
}

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #6
Actually W3C specifies that getElementById returns the first element
with the supplied id, so the functionality of that part should be
standard (Although giving multiple elements the same id is certainly bad
programming practice); I was just giving the original poster what they
wanted, a way to do that silly little trick. Thanks for the info, makes
sense. What about the insertAdjacent? Also not in the official DOM
methinks.
In article <41***********************@newsread4.arcor-online.net>,
ma*******@yahoo.de says...
same id attribute value and what happens with document.getElementById is

Jul 23 '05 #7
John Doe wrote:
Actually W3C specifies that getElementById returns the first element
with the supplied id,
Rubbish.

"ID
This attribute assigns a name to an element. This name must be
unique in a document.

"...The id attribute assigns a unique identifier to an
element...

"...Note that the French "msg1" and the English "msg1" may not
appear in the same document since they share the same id
value."

<URL:http://www.w3.org/TR/html4/struct/global.html#adef-id>

You will also find a number of references in the anchors section
highlighting that *ID must be unique*
<URL:http://www.w3.org/TR/html4/struct/links.html#anchors-with-id>
The specification absolutely unequivocal: ID must be unique.

Furthermore, ID and NAME share the same namespace so the only
way to have an identical name and id in the same document is for
them to be on the same element (either A, APPLET, FORM, FRAME,
IFRAME, IMG, or MAP), and in that case they *must* be
identical. Name need not be unique, but when used as an anchor
it must be.

Most browsers will return the first element if two have
identical IDs - but it is not part of the W3C standard.

so the functionality of that part should be
standard


No, it's not. It's just that the major browsers do it that way
to play nice and not barf if you make a mistake.

--
Zif
Jul 23 '05 #8
John Doe wrote:
Actually W3C specifies that getElementById returns the first element
with the supplied id,
Rubbish.

The W3C DOM Level 1 spec says:

"getElementById
Returns the Element whose id is given by elementId. If no such
element exists, returns null. Behavior is not defined if more
than one element has this id.

"Parameters
elementId
The unique id value for an element."

<URL:http://www.w3.org/TR/REC-DOM-Level-1/level-one-html.html#ID-36113835>

In other words, it must be unique and if not, the behavior is
not defined. Quite a bit different from your guess - got a
reference?

Further more, the HTML specification is even more explicit:

"ID
This attribute assigns a name to an element. This name must be
unique in a document.

"...The id attribute assigns a unique identifier to an
element...

"...Note that the French "msg1" and the English "msg1" may not
appear in the same document since they share the same id
value."

<URL:http://www.w3.org/TR/html4/struct/global.html#adef-id>

You will also find a number of references in the anchors section
highlighting that *ID must be unique*
<URL:http://www.w3.org/TR/html4/struct/links.html#anchors-with-id>
The specification absolutely unequivocal: ID must be unique.

Furthermore, ID and NAME share the same namespace so the only
way to have an identical name and id in the same document is for
them to be on the same element (either A, APPLET, FORM, FRAME,
IFRAME, IMG, or MAP), and in that case they *must* be
identical. Name need not be unique, but when used as an anchor
it must be.

Most browsers will return the first element if two have
identical IDs - but it is not part of the W3C standard.
so the functionality of that part should be standard
Not at all. The "functionality" is undefined.
standard (Although giving multiple elements the same id is certainly bad
programming practice);


Not just bad, but it will create invalid HTML.

--
Rob
Jul 23 '05 #9
John Doe wrote:
Actually W3C specifies that getElementById returns the first element
with the supplied id...
Rubbish.

The W3C DOM 1 and 3 specs say the same thing:

"getElementById
"Returns the Element that has an ID attribute with the given
value. If no such element exists, this returns null. If more
than one element has an ID attribute with that value, *what is
returned is undefined.*" (my emphasis)

<URL:http://www.w3.org/TR/2004/REC-DOM-Level-3-Core-20040407/core.html#ID-getElBId>

The W3C specification actually says to return undefined. Most
browsers don't, being somewhat sympathetic they tend to return
the first element that matches. However, it is *not* the
behaviour specified by the W3C.

The HTML specification is unwavering in its insistence that id
be unique in a document:

"ID
This attribute assigns a name to an element. This name must be
unique in a document.

"...The id attribute assigns a unique identifier to an
element...

"...Note that the French "msg1" and the English "msg1" may not
appear in the same document since they share the same id
value."

<URL:http://www.w3.org/TR/html4/struct/global.html#adef-id>

You will also find a number of references in the anchors section
highlighting that *ID must be unique*
<URL:http://www.w3.org/TR/html4/struct/links.html#anchors-with-id>

The specification is absolutely unequivocal: ID must be unique.

Furthermore, ID and NAME share the same namespace so the only
way to have an identical name and id in the same document is for
them to be on the same element (either A, APPLET, FORM, FRAME,
IFRAME, IMG, or MAP) and in that case they *must* be
identical. Name need not always be unique, but when used as an
anchor, it must be.

Most browsers will return the first element if two have
identical IDs - but it is not part of the W3C standard.
...so the functionality of that part should be
standard...
The functionality is common, but not standard.

Browsers that return the first element with the duplicate ID do
so for the sake of tolerance of invalid markup, not because they
are compelled to do so for standards compliance. Making the
operation of pages dependent on this "feature" is like refusing
to add closing </p> tags because nearly all browsers infer them
anyway.
...(Although giving multiple elements the same id is certainly bad
programming practice)


Not just bad practice, it creates invalid HTML and depends on
the successful operation of an unspecified "feature".
--
Zif
Jul 23 '05 #10


John Doe wrote:
Actually W3C specifies that getElementById returns the first element
with the supplied id, so the functionality of that part should be
standard
No idea where you think the W3C states that but the current DOM Level 2
Core in
<http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document>
clearly says about getElementById on the document node:
"Behavior is not defined if more than one element has this ID."
What about the insertAdjacent? Also not in the official DOM
methinks.


insertAdjacentHTML in IE's DOM cannot be done with DOM Level 1 and 2 API
as it requires parsing of markup obviously, with Mozilla however it
can be emulated as Mozilla has an extension to parse HTML.
insertAdjacentElement can be done but while in IE's DOM you call that
method on one node and then the argument e.g. 'afterEnd' decides on the
actual parent the node is inserted in in the W3C DOM you will need to
have your code find the right place to insert so
element.insertAdjacentElement('beforeEnd', newElement)
would translate to
element.appendChild(newElement)
and
element.insertAdjacentElement('afterBegin', newElement)
to
element.insertBefore(newElement, element.firstChild)
while for
element.insertAdjacentElement('beforeBegin', newElement);
you need
var parentNode = element.parentNode;
if (parentNode) {
parentNode.insertBefore(newElement, element);
}
and for
element.insertAdjacentElement('afterEnd', newElement)
should be
var parentNode = element.parentNode;
if (parentNode) {
parentNode.insertBefore(newElement, element.nextSibling);
}

All written down from memory and not tested at all so don't rely blindly
on that.

--

Martin Honnen
http://JavaScript.FAQTs.com/
Jul 23 '05 #11
>
No idea where you think the W3C states that but the current DOM Level 2
Core in
<http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document>
clearly says about getElementById on the document node:
"Behavior is not defined if more than one element has this ID."

You are right of course. I feel both sheepish and chastened. Don't
know where I got that. It wasn't from M$ and it (obviously) wasn't from
the W3C. I'll be more careful about who I'm relying on in the future.
Thanks for the tip on the alternative to adjacentelement code.
Jul 23 '05 #12
JRS: In article <sS*****************@news.optus.net.au>, dated Fri, 28
Jan 2005 05:14:00, seen in news:comp.lang.javascript, Zifud
<Zi***@hotmail.com> posted :

The W3C DOM 1 and 3 specs say the same thing:

"getElementById
"Returns the Element that has an ID attribute with the given
value. If no such element exists, this returns null. If more
than one element has an ID attribute with that value, *what is
returned is undefined.*" (my emphasis)

<URL:http://www.w3.org/TR/2004/REC-DOM-Le.../core.html#ID-
getElBId>

The W3C specification actually says to return undefined.

I don't know what W3C intended to mean.

But the quoted words mean that what is returned is nor defined,
uncertain, unreliable, etc.; not that the special state _undefined_ is
required to be returned.

However, if the quoted "undefined" was textually distinguished, it might
stand for the special value.

Tip to W3C and others : when defining a language in which a special
value called "undefined" exists, never use the word "undefined" where
"not defined" would do.

--
© John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #13
Dr John Stockton wrote:
<snip>
Tip to W3C and others : when defining a language in which
a special value called "undefined" exists, never use the
word "undefined" where "not defined" would do.


The W3C DOM specifications are intended to be programming language
neutral, expressing their interface definitions in IDL (rather than any
of the languages for which they explicitly provide binding documents).
As a result the term 'undefined' should have no meaning other than its
common English usage in that context. Within the DOM binding documents
specifically aimed at ECMAScript the term might be more ambiguous.

Richard.
Jul 23 '05 #14

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Manlio Perillo | last post by:
Hi. This post follows "does python have useless destructors". I'm not an expert, so I hope what I will write is meaningfull and clear. Actually in Python there is no possibility to write code...
2
by: Davis King | last post by:
Can I assume that std::swap will not throw when it is used to swap std::string objects? In the standard it says that the swap() std::string member function runs in constant time. I didn't see...
38
by: JKop | last post by:
union SignedChoice{ long with_sign; unsigned long without_sign; }; int main() { SignedChoice data;
14
by: pras.vaidya | last post by:
hi, please help me with this problem : - how to swap two addresses .For eg variable i is located at 2000 and j at 3000 . Now i call swap function . Result should be that i should be now having...
9
by: Jongmin Lee | last post by:
Hi Everybody, I have very simple code snippet to explain my problem. Class "Swap" is construncted in "Main" with two initial variables. Later, "Swap" class is going to swap those two...
28
by: Jess | last post by:
Hello, It is said that if I implement a "swap" member function, then it should never throw any exception. However, if I implement "swap" non- member function, then the restriction doesn't...
3
by: .rhavin grobert | last post by:
guess you have two classes (A and B) and you have two objects (C1 and C2) of a class C that is defined as class C: public A, public B can I *somehow* swap B of C1 and B of C2? To make myself...
4
by: George2 | last post by:
Hello everyone, The following swap technique is used to make assignment operator exception safe (means even if there is exception, the current object instance's state is invariant). It used...
21
by: raylopez99 | last post by:
In the otherwise excellent book C# 3.0 in a Nutshell by Albahari et al. (3rd edition) (highly recommended--it's packed with information, and is a desktop reference book) the following statement is...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.