473,703 Members | 2,399 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Question about cloneNode behavior

I have a button on a page whose onclick funtion is posted below. I am
basically trying to get all the spans in the page and list them in 2
columns. I get the list of spans using getElementsByTa gName('span').

I dont want to move the spans themselves into my 2 column list(i.e I
want them to stay where they are on the page), so I figured I needed
to clone each span. Each time I make a clone, the clone somehow gets
added to my original list of spans, so I end up in an infinite loop
adding the first few elements again and again. How is this supposed to
be done? Javascript n00b here...any advise is greatly
appreciated...

function getSpans()
{
var allspans=docume nt.getElementsB yTagName("span" );
var infoDiv = null;
var tmp;
for(var element, i=0;element=all spans[i];i++)
{
tmp=element.clo neNode(true);
alert(i +' '+tmp.innerHTML +' ' +allspans.lengt h); <<<<<
allspans keeps increasing
if( i%2 == 0 ){
if( i!=0 ) list1.appendChi ld(infoDiv);
infoDiv=documen t.createElement ('div');
}
infoDiv.appendC hild(tmp);
}
}

list1 is a div id

Thanks
Jun 27 '08 #1
3 1498
On Apr 16, 2:32 pm, santosh....@gma il.com wrote:
I have a button on a page whose onclick funtion is posted below. I am
basically trying to get all the spans in the page and list them in 2
columns. I get the list of spans using getElementsByTa gName('span').

I dont want to move the spans themselves into my 2 column list(i.e I
want them to stay where they are on the page), so I figured I needed
to clone each span. Each time I make a clone, the clone somehow gets
added to my original list of spans, so I end up in an infinite loop
adding the first few elements again and again.
The collection returned by getElementsByTa gName is live, that is, as
you add more spans to the document, more are added to your collection.

How is this supposed to
be done?
Convert the collection to an array, something like:

function toArray(obj) {

if (typeof obj.length != 'number') { return [obj]; }

var result = [];
for (var i=0, len=obj.length; i<len; i++) {
result.push(obj[i]);
}
return result;
}

You can also work backward through the collection using its initial
length if you are adding the spans lower in the DOM than the last in
the initial collection, but that doesn't seem to be a good idea here
(and can cause maintenance issues anyway).

Javascript n00b here...any advise is greatly
appreciated...

function getSpans()
{
var allspans=docume nt.getElementsB yTagName("span" );
var infoDiv = null;
var tmp;
for(var element, i=0;element=all spans[i];i++)
Why not the more common:

var element;
for (var i=0, len=allspans.le ngth; i<len; i++) {
element = allspans[i];
{
tmp=element.clo neNode(true);
alert(i +' '+tmp.innerHTML +' ' +allspans.lengt h); <<<<<
allspans keeps increasing
if( i%2 == 0 ){
You could just use i%2
if( i!=0 ) list1.appendChi ld(infoDiv);
Don't expect element IDs to be global variables, that is an IE
invention. Use getElementById.

infoDiv=documen t.createElement ('div');
}
infoDiv.appendC hild(tmp);
}

}

list1 is a div id
function getSpans(id) {

var target = document.getEle mentById(id);
var allspans = toArray(documen t.getElementsBy TagName('span') );
var div = document.create Element('div');

for (var i=0, len=allspans.le ngth; i<len; i++) {
div.appendChild (allspans[i].cloneNode(true ));
}

target.appendCh ild(div);
}

Needs a bit of feature detection and testing, but shows the concept I
hope.
--
Rob

Jun 27 '08 #2
Thanks a lot!

The toArray() was what I needed. Didn't know about live collections
and lost a bit of hair trying to figure out what it was doing.

About the 'for' loop style, it's part of some existing code and I
hadn't actually given it any thought until you pointed out the
conventional form. It works fine though. The i%2==0 is required as I
am trying to create a div every 2 spans.

Thanks once again for all the pointers...much appreciated.
Jun 27 '08 #3
RobG wrote:
function toArray(obj) {

if (typeof obj.length != 'number') { return [obj]; }

var result = [];
for (var i=0, len=obj.length; i<len; i++) {
result.push(obj[i]);
}
return result;
}
Given that Array.prototype .push() requires JScript 5.5, much more efficient
and equally compatible is

function toArray(obj)
{
return [].slice.call(obj );
}

See http://PointedEars.de/es-matrix
PointedEars
--
realism: HTML 4.01 Strict
evangelism: XHTML 1.0 Strict
madness: XHTML 1.1 as application/xhtml+xml
-- Bjoern Hoehrmann
Jun 27 '08 #4

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

Similar topics

1
2120
by: MonkeyBoy | last post by:
I am doing some some HTML manipulation in client-side script (IE5.x and IE6.x browsers only). Something like.. var tmpHTML = oTable.outerHTML // do something to the HTML her oTable.outerHTML = tmpHTML Before the changes, client-side .Net field validators (RegularExpressionValidator, RangeValidator, etc.) work fine... after the changes, the modified HTML works correctly but the validators stop functioning. Seems that the onchange handler...
8
1874
by: Richard Trahan | last post by:
I have the following line of code: var newopt = document.createElement("option"); I addChild this to a select list node and it works fine. I want to attach an object reference to newopt, but the system doesn't allow me to do this: newopt.createAttribute("graph")
3
1667
by: Marco Rizzi | last post by:
Hi all, i'm trying to add same node to XmlDocument. This is Xml that I want to create: <TableColumns> <TableColumn><Width>1.5in</Width></TableColumn> <TableColumn><Width>1.5in</Width></TableColumn> <TableColumn><Width>1.5in</Width></TableColumn> <TableColumn><Width>1.5in</Width></TableColumn> </TableColumns>
1
1262
by: Petr Felzmann | last post by:
Hi, why the duration of call the CloneNode(true) is steadily increasing? First call is 0.004s and 100th is 0.16s! XML file is 5kB only, no disk swap. XmlDataDocument xml = new XmlDataDocument(); xml.Load(@"C:\foo.xml"); for(int i = 0; i < 100; i++) { XmlNode node = xml.CloneNode(true);
0
1908
by: Sullivan WxPyQtKinter | last post by:
Hi, I am now using minidom for my current development. I use cloneNode method in Element object, but it just does not work. The test code is very simple as follows: =========CODE============== from xml.dom.minidom import * a=Element('see') print a.toprettyxml() b=a.cloneNode(True)
2
4600
by: Csaba Gabor | last post by:
One of the things that I never understood was the motivation for not being able to iterate over the event listeners added via ..addEventListener It's particularly vexing because if you do element.cloneNode(bDeep), you frequently get a stunted clone, often with several key features missing, and one of these is associated event handlers. Of course, it could be the case that the event handlers have a closure including a reference to the...
1
6668
by: jaktharkhan | last post by:
Hi, I really really need help in trying to figure out how can I do a CloneNode on an Iframe where the cloned IFRAME clones with all its contents?. Basically what I am doing is dynamically building a table with Iframes inside it. The problem is I just want to build one Iframe because the contents of it can be very complex. After my Iframe is built I just want to clone the iframe as many times as I need later. I cannot use an HTML file and...
0
8667
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9249
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9116
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9013
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8961
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7860
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4428
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3120
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.