473,881 Members | 1,673 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

javascript recursive appendChild function

Hi all,

I am coding an AJAX DHTML whatever application and I was fed up with
always typing a lot of appendChild() functions.

I created a custom one called append_children () and wanted to share it
if anyone need such a function.

function append_children () {
var a = append_children .arguments;
for ( var i = a.length - 1; i > 0 ; i-- ) {
try {
a[i-1].appendChild(a[i]);
} catch(e) {
for ( var j = 0; j < a[i].length; j++ ) {
append_children (a[i-1], a[i][j]);
}
}
}
}

You can see a working example with this URL :
http://amisphere.blogspot.com/2005/0...pendchild.html

If anyone has some suggestions about modifications or other ways to
achieve this task, please post...

Sam

Aug 1 '05 #1
2 10856


sa*********@gma il.com wrote:

I am coding an AJAX DHTML whatever application and I was fed up with
always typing a lot of appendChild() functions.

I created a custom one called append_children () and wanted to share it
if anyone need such a function.

function append_children () {
var a = append_children .arguments;
You should simply use
var a = arguments;
here as functionName.ar guments is deprecated.
for ( var i = a.length - 1; i > 0 ; i-- ) {
try {
a[i-1].appendChild(a[i]);
} catch(e) {
for ( var j = 0; j < a[i].length; j++ ) {
append_children (a[i-1], a[i][j]);
}
}
}
}

You can see a working example with this URL :
http://amisphere.blogspot.com/2005/0...pendchild.html


You do not explain in your post here what is supposed to be passed to
the function but in the article at that URL you do so I borrow from there:

You want to replace the code

function menu_create() {
// create HTML nodes
menu_div = document.create Element('div');
menu_span1 = document.create Element('span') ;
menu_span1_txt = document.create TextNode(' Buy ');
menu_span2 = document.create Element('span') ;
menu_span2_txt = document.create TextNode(' Sell ');
menu_span3 = document.create Element('span') ;
menu_span3_txt = document.create TextNode(' Share ');

// join the nodes together
menu_span1.appe ndChild(menu_sp an1_txt);
menu_span2.appe ndChild(menu_sp an2_txt);
menu_span3.appe ndChild(menu_sp an3_txt);
menu_div.append Child(menu_span 1);
menu_div.append Child(menu_span 2);
menu_div.append Child(menu_span 3);

// show the menu on the page
document.body.a ppendChild(menu _div);
}

menu_create();

with the code

function append_children () {
var a = append_children .arguments;
for ( var i = a.length - 1; i > 0 ; i-- ) {
try {
a[i-1].appendChild(a[i]);
} catch(e) {
for ( var j = 0; j < a[i].length; j++ ) {
append_children (a[i-1], a[i][j]);
} } }
}

function menu_create() {
// create HTML nodes
menu_div = document.create Element('div');
menu_span1 = document.create Element('span') ;
menu_span1_txt = document.create TextNode(' Buy ');
menu_span2 = document.create Element('span') ;
menu_span2_txt = document.create TextNode(' Sell ');
menu_span3 = document.create Element('span') ;
menu_span3_txt = document.create TextNode(' Share ');

// join the nodes together and show the menu on the page
append_children (document.body, menu_div, [[menu_span1, menu_span1_txt],
[menu_span2, menu_span2_txt],[menu_span3, menu_span3_txt]]);

}

menu_create();
That does not create the same DOM structure however, the original code
creates the text nodes as child nodes of the <span> elements e.g.

<div><span> Buy </span><span> Sell </span><span> Share </span></div>

while with your function (if it works at all) you get the <span>
elements and the text nodes as siblings e.g.

<div><span></span> Buy <span></span> Sell <span></span> Share </div>

That is what happens with Mozilla and IE, Opera 8 does not intend to
play to your rules "if the child element is an array, the appendChild
function fails" and creates only a <div> element.

So you need to recode your function to achieve the same structure as the
original code.

And you should try to avoid try/catch respectively hoping on some error
being thrown, if you know that some elements in the array passed in can
be arrays itself then you can check whether the element has a length
property and then process it recursively as you want.
--

Martin Honnen
http://JavaScript.FAQTs.com/
Aug 1 '05 #2
Hi Martin,
You should simply use
var a = arguments;
here as functionName.ar guments is deprecated.
Thanks for the tip, i just used my Javascript Bible 5th edition where
it still shows the functionName.ar guments as an example.
You do not explain in your post here what is supposed to be passed to
the function but in the article at that URL you do so I borrow from there:

You want to replace the code

function menu_create() {
// create HTML nodes
menu_div = document.create Element('div'); .... }

menu_create();
That does not create the same DOM structure however, the original code
creates the text nodes as child nodes of the <span> elements e.g.

<div><span> Buy </span><span> Sell </span><span> Share </span></div>

while with your function (if it works at all) you get the <span>
elements and the text nodes as siblings e.g.

<div><span></span> Buy <span></span> Sell <span></span> Share </div>

That is what happens with Mozilla and IE, Opera 8 does not intend to
play to your rules "if the child element is an array, the appendChild
function fails" and creates only a <div> element.

Oops ! :) I feel so stupid now...

I checked the example with the DOM Inspector, looks like i was too
tired to see my mistakes.
So you need to recode your function to achieve the same structure as the
original code.

Sir, yes, sir.
And you should try to avoid try/catch respectively hoping on some error
being thrown, if you know that some elements in the array passed in can
be arrays itself then you can check whether the element has a length
property and then process it recursively as you want.


I used the try/catch method to detect whether an element is an array or
not because there is no ( typeof x == array ) and a TextNode has a
length property.

You are right, this is not elegant at all. With a night of sleep, a
better method is :

if ( element.nodeTyp e ) alert( element + ' is a node.');
else alert( element + ' should be an array.');

Well, i have recoded the function with my brain plugged. I'm not very
satisfied but the final version works fine with Mozilla, IE and Safari.

I wanted to use the arguments.calle e.caller but it doesn't work with
Safari, so i have done it this way :

I want to append a document structure at once, modeled with arrays.

To obtain this structure :
<div><span></span><span></span></div><span></span>

I feed the append_children function this way :
append_children ([[document.body, div, [[span1, span1_txt], [span2,
span2_txt]]], [document.body, [span3, span3_txt]]]);

The solution works this way :
1. I use a recursive function to remove the arrays
2. While removing those arrays, i record the array structures inside a
global variable
3. I use this structure variable to append the children nodes to the
document

Working example :
http://test.amisphere.com/code/append_children.html

Can you make a few comments on what i could improve in the code ?

--
Sam
http://amisphere.blogspot.com/
--

Aug 3 '05 #3

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

Similar topics

4
3855
by: JesusFreak | last post by:
From: us_traveller@yahoo.com (JesusFreak) Newsgroups: microsoft.public.scripting.jscript Subject: toolbar script problem NNTP-Posting-Host: 192.92.126.136 Recently, I downloaded the following beautiful script "http://javascript.internet.com/navigation/toolbar-menu.html". It works like a charm. I made my webpage in frames, where the nav-frame shows the menubar, so whenever I click a link in the menubar, it opens in the frame below. But...
4
6323
by: Sergio del Amo | last post by:
i, I have the next html page <html> <head> <script> <!-- function insertcode() { var code ="<p> blablabal babala babababab</p><h1>here comes header</h1><span>fadfafa<a href=\"fadfaf\">anchor</a>blalbababa</span>"
4
6335
by: bboyle18 | last post by:
Hi, I am working with a table sorting script which can be found here http://www.workingwith.me.uk/articles/scripting/standardista_table_sorting This script works very nicely, but when there is a large amount of data to sort e.g > 200 then there is a slight delay in the table sort. To cater for this I want to provide some feedback to the user to inform them that the sort function is processing. My idea is to add a "sorting...." message...
7
3232
by: julian.tklim | last post by:
Hi, I need to build an editable Datagrid with add & delete buttons on each row using javascript. DataGrid need not be pre-populated with values. To make the thing complicated, one of the column need to be a date picker field. I know things will be easier with ASPX datagrid.
3
3478
by: SM | last post by:
Hello, Im trying to access elements in my XML file using the JavaScript DOM but i'm not sure how. I use AJAX to access the XML and then use the responseXML property to access the XML file data. I want to extract all the tracks from a specific CD. Right now, im using an array to stock all the data but its just a question of time before everything blows up because of the size of the array. Thats why im want to use an XML file (later i will...
0
1305
by: Kaushik C P | last post by:
Can you tell me , why this code does not run: <%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="AJAX6.aspx.cs" Inherits="Experiments_AJAX_AJAX6" Title="XML and SQL" %> <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">
6
1983
by: ApOG | last post by:
Hello everyone, I have this javascript code working perfectly with IE, but with firefox nothing happens when running the function... function add_div_field () { var ni = document.getElementById('upload_div'); var num = contador_upload++; var div = document.createElement("div"); var div_name = "filediv"+num; div.setAttribute("id",div_name);
6
2024
by: ismomo | last post by:
Hi all, I am facing a problem in recursive. I would like to create node strcuture similar with the xml structure shown below. However, I am not able to create the node with the sub I written in perl. I got the error, Can't call method "appendChild" on an undefined value at the $top_xml_node->appendChild($sub_node);. Anybody can help me? I have stuck at this function. Thanks. <organizations default="TOC1"> <organization> ...
3
2364
chathura86
by: chathura86 | last post by:
hi i wrote the following code to populate a table dynamically it works perfectly on Firefox but not in IE 7 does not show any errors on IE7 either please help me
0
9776
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
11095
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
10399
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...
1
7952
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5780
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...
0
5976
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4597
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
2
4194
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3223
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.