473,657 Members | 2,593 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

replaceNode


Hi,
I am using JavaScript to replace a node in HTML Tree. Currently I
am using Mozilla and localhost to server files.
1. Eveytime I replace a node with a new node, the size of the new texts
seems to increase and some extra lines seem to appear in the page.
I am replacing a node with a new node, which is suppose to have the
line "<H2> Text Text Text </H2>" stored in a variable (say A).

var newnode = document.create Element("H2");
newnode.innerHT ML = A;
oldnode.replace Child(newnode,e xisting_node);

"Text Text Text " when gets displayed seem bigger than actual size of
H2 and extra lines also seem to appear(above and below "Text Text Text
") in the newly displayed page. Any idea why this might be happening?

2. Once I display the new page (modified from existing by adding extra
nodes and ...), the source code of the page however is not changed and
thus the DOM structure (although some new nodes were added) is also
same. If I am to make some new modifications to the newly formed page
(and not the original page), will I face problems??? any solution for
that??

Thanks
Anand
--
Anand
------------------------------------------------------------------------
Anand's Profile: http://www.highdots.com/forums/member.php?userid=72
View this thread: http://www.highdots.com/forums/showthread.php?t=1746467

Jul 23 '05 #1
10 7115
Anand wrote:
Hi,
I am using JavaScript to replace a node in HTML Tree. Currently I
am using Mozilla and localhost to server files.
1. Eveytime I replace a node with a new node, the size of the new texts
seems to increase and some extra lines seem to appear in the page.
I am replacing a node with a new node, which is suppose to have the
line "<H2> Text Text Text </H2>" stored in a variable (say A).

var newnode = document.create Element("H2");
newnode.innerHT ML = A;
oldnode.replace Child(newnode,e xisting_node);

"Text Text Text " when gets displayed seem bigger than actual size of
H2 and extra lines also seem to appear(above and below "Text Text Text
") in the newly displayed page. Any idea why this might be happening?
You create a new H2 element with createElement, then you create
another when you use innerHTML with '<H2>....</H2>'. Try:

var A = "Text Text Text"
var newnode = document.create Element("H2");
newnode.appendC hild(document.c reateTextNode(A ));
oldnode.replace Child(newnode,e xisting_node);

2. Once I display the new page (modified from existing by adding extra
nodes and ...), the source code of the page however is not changed and
thus the DOM structure (although some new nodes were added) is also
same. If I am to make some new modifications to the newly formed page
(and not the original page), will I face problems??? any solution for
that??


The source is changed, but the browser will only show you the original
source.

<URL:http://groups.google.c om.au/group/comp.lang.javas cript/browse_thread/thread/8acbf8295c3cedc 9/0efaa271ed564bf b?q=view+source +code+javascrip t+innerHTML&rnu m=1&hl=en#0efaa 271ed564bfb>

Or copy/paste the following into the address bar - you could save it
as a bookmark for frequent use:

javascript:CODE =window.open("" , " CODE ", "height=700 , width=800");
CODE.document.w rite("<FORM NAME=\"SPAM\">< TEXTAREA NAME=\"SRC\"
ROWS=45 COLS=82></TEXTAREA></FORM>");
CODE.document.S PAM.SRC.value=d ocument.documen tElement.innerH TML; void 0

It should be pasted as a single line with no returns - make sure none
have been added or whitespace added where it shouldn't be.
--
Rob
Jul 23 '05 #2

Hi,
For this first one where you suggested me to:

var A = "Text Text Text"
var newnode = document.create Element("H2");
newnode.appendC hild(document.c reateTextNode(A ));
oldnode.replace Child(newnode,e xisting_node);

What this does is it puts Text Text Text to the proper place. however
my variable 'A' has tags included in it. ie. <h2> Text Text Text </h2>
and I wouldn't want to display the tags which will happen when we
create a text node out of A. Thats why I used innerHTML.

Thanks for your reply. Please suggest if I am getting it wrong.

Anand
--
Anand
------------------------------------------------------------------------
Anand's Profile: http://www.highdots.com/forums/member.php?userid=72
View this thread: http://www.highdots.com/forums/showthread.php?t=1746467

Jul 23 '05 #3
Anand wrote:
Hi,
For this first one where you suggested me to:

var A = "Text Text Text"
var newnode = document.create Element("H2");
newnode.appendC hild(document.c reateTextNode(A ));
oldnode.replace Child(newnode,e xisting_node);

What this does is it puts Text Text Text to the proper place. however
my variable 'A' has tags included in it. ie. <h2> Text Text Text </h2>
and I wouldn't want to display the tags which will happen when we
create a text node out of A. Thats why I used innerHTML.


Your difficulty is caused by mixing createElement with innerHTML. If
the *only* content of 'oldnode' is 'existing_node' , then:

var A = '<h2> ... </h2>'
oldnode.innerHT ML = A;

will completely replace the content of oldnode with the text in 'A'.
Since A contains HTML markup, innerHTML will cause the browser to
parse the HTML (note, there is no public specification for innerHTML,
I'm just reporting observed behaviour).

However, I suspect that 'existing_node' is just one of many children
of 'oldnode' and that you are trying to replace just the one node. In
that case you need a kind of 'placeholder' to put the innerHTML into.
I believe outerHTML does the trick, essentially replacing the HTML
of 'existing_node' with 'A' - but that is almost exclusive to IE and
so not very web-friendly.

You may want to play with createDocumentF ragment:

<URL:http://www.mozilla.org/docs/dom/domref/dom_doc_ref45.h tml#1025874>

You should use feature detection to ensure it is supported, perhaps
try document fragment, then outerHTML.

--
Rob
Jul 23 '05 #4
RobG wrote:
[...]

You may want to play with createDocumentF ragment:

<URL:http://www.mozilla.org/docs/dom/domref/dom_doc_ref45.h tml#1025874>

You should use feature detection to ensure it is supported, perhaps try
document fragment, then outerHTML.


createDocumentF ragment doesn't seem to help - you can't add content
using innerHTML as far as I can tell. One strategy is to add a new
div to the document and set the display to 'none'. Add the new HTML
using innerHTML, clone the content, add it where you want, then delete
the temporary div.

Sample here:

<div id="yy">
<h2>here is one</h2>
<h2 id="zz">here is two</h2>
</div>
<input type="button" value="replace two" onclick="

var A = '<h2> New text </h2>';
var oldnode = document.getEle mentById('yy');
var existing_node = document.getEle mentById('zz');

// Create a temp div
var tNode = document.create Element('div');

// Set its display to none (should stop any undesirable UI effects)
tNode.style.dis play = 'none';

// Add it to the document
document.body.a ppendChild(tNod e);

// Use innerHTML to generate elements from the HTML
tNode.innerHTML = A;

// Clone the node that was created
var xNode = tNode.firstChil d.cloneNode(tru e);

// Replace 'existing_node' with the new cloned node
existing_node.p arentNode.repla ceChild(xNode, existing_node);

// Delete the temp div and its content
tNode.parentNod e.removeChild(t Node);

">

It assumes that only one child is created, though it could contain
lots of other stuff too. Note that you must ensure that valid HTML is
generated or unexpected results will occur. Some browsers will let
you use innerHTML on elements before they are added to the document,
but some don't.
--
Rob
Jul 23 '05 #5

Thanks for your replies.
I tried the method you suggested in the last reply. It was interesting
to note that, instead of the new node [var A = '<h2> New text </h2>';]
replacing the existing node, the existing node totally diappears from
the list.

I have attached part of Dom tree I am dealing with. I need to replace
one of the TR under 'questionmenu' and my variable has
'<tr><td><a href='http://www.kkk.com'>Qu estion 2</a></td>'

I applied your method for this DOM str. The existing node disappears.
The other thing is, I seem to be having problem with 'tr' and 'td'. I
haven't tried your method but with other tags like 'h2',

var newnode = createElement() ;
newnode.innerHT ML = A;
parent.replaceC hild(newnode,ex isting_node);

works fine. With trs and tds, a small gap seems to have been placed
instead of the newone. When I check the innerHTML of newnode, it still
hold the actual value that I need to replace with. However, doesn't
work......

I am still to try outerHTML.

Thanks
Anand
+-------------------------------------------------------------------+
|Filename: dom.JPG |
|Download: http://www.highdots.co m/forums/attachment.php? attachmentid=15 6|
+-------------------------------------------------------------------+

--
Anand
------------------------------------------------------------------------
Anand's Profile: http://www.highdots.com/forums/member.php?userid=72
View this thread: http://www.highdots.com/forums/showthread.php?t=1746467

Jul 23 '05 #6
Anand wrote:
Thanks for your replies.
I tried the method you suggested in the last reply. It was interesting
to note that, instead of the new node [var A = '<h2> New text </h2>';]
replacing the existing node, the existing node totally diappears from
the list.
It worked for me in Safari, Firefox (Mac & Windows) and IE (Windows).
You may want to set the display of the clone to '' as it may have
inherited the property from the original parent:

// Clone the node that was created
var xNode = tNode.firstChil d.cloneNode(tru e);
xNode.style.dis play = '';

I have attached part of Dom tree I am dealing with. I need to replace
one of the TR under 'questionmenu' and my variable has
'<tr><td><a href='http://www.kkk.com'>Qu estion 2</a></td>'
Do not use innerHTML to replace any table elements - though it can be
used to replace an entire table or the content of a cell.

<URL:http://msdn.microsoft. com/workshop/browser/mshtml/reference/ifaces/ihtmlelement/innerhtml.asp>

Your string is also missing a closing '</tr>' - closing TR tags are
optional in HTML, but I think it's better to keep it complete.

I applied your method for this DOM str. The existing node disappears.
The other thing is, I seem to be having problem with 'tr' and 'td'. I
haven't tried your method but with other tags like 'h2',

var newnode = createElement() ;
newnode.innerHT ML = A;
parent.replaceC hild(newnode,ex isting_node);
That will not work in all browsers that support innerHTML, though it
seems OK some.

works fine. With trs and tds, a small gap seems to have been placed
instead of the newone. When I check the innerHTML of newnode, it still
hold the actual value that I need to replace with. However, doesn't
work......

I am still to try outerHTML.


outerHTML is IE pretty much IE only, so only use it if this is for an
intranet and everyone uses IE. You can do a reasonable emulation with
Mozilla using createContextua lFragment, which is part of the Geko
extensions to the range interface, but it's Mozilla only AFAIK.

<URL:http://www.mozilla.org/docs/dom/domref/dom_range_ref26 .html#1003785>

See below for one I baked earlier as an exercise.

In regard to the extra space when adding nodes in Firefox, that seems to
be a function of the layout. For the new elements, set the margin &
padding to 0 (or some fixed value you like) and things settle down again.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/str ict.dtd">
<html>
<head>
<title>outerHTM L play</title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<style type="text/css">
body, div, h2 { margin: 0; padding: 0}

#zz {
border: 1px solid red;
background-color: #ddddff;
}
</style>
<script type="text/javascript">

function timeNow() {
var t = new Date();
var s = preZ(t.getHours ())
+ ':' + preZ(t.getMinut es())
+ ':' + preZ(t.getSecon ds())
t = t*1 + '';
s += '.' + t.substring(t.l ength-3);
return s;
}

function preZ( x ) {
return ( 10 > x )? '0' + x : x;
}

/*
Add a temporary div with display none,
insert HTML using innerHTML,
clone the node created
replace the old node with the clone
delete the temporary div and its content.

Only works if innerHTML only created one child node of the
temporary DIV. But that child may have many children
and decedents.
*/
function divMethod(){
var A = '<h2 id="zz"> Now is ' + timeNow() + ' </h2>';
var oldnode = document.getEle mentById('yy');
var existing_node = document.getEle mentById('zz');

// Create a temp div
var tNode = document.create Element('div');

// Set its display to none (should stop any undesirable UI effects)
tNode.style.dis play = 'none';

// Add it to the document
document.body.a ppendChild(tNod e);

// Use innerHTML to generate elements from the HTML
tNode.innerHTML = A;

// Clone the node that was created
var xNode = tNode.firstChil d.cloneNode(tru e);
xNode.style.dis play = '';

// Replace 'existing_node' with the new cloned node
existing_node.p arentNode.repla ceChild(xNode, existing_node);

// Delete the temp div and its content
tNode.parentNod e.removeChild(t Node);
}

/*
Use outerHTML if it's available,
if not, create a document range (if supported)
then use createContextua lFragment (if supported)
and replace the old node
*/
function pseudoOuterHTML () {
var A = '<h2 id="zz"> Now is ' + timeNow() + ' </h2>';
var oldnode = document.getEle mentById('yy');
var existing_node = document.getEle mentById('zz');

// if ( existing_node.o wnerDocument.cr eateRange ) {
if ( document.create Range ) {

// Where createRange supported
var r = document.create Range();
r.selectNode(ex isting_node);

// And createContextua lFragment supported
// It's a Mozilla extension...
if ( r.createContext ualFragment ) {
var frag = r.createContext ualFragment(A);
existing_node.p arentNode.repla ceChild(frag, existing_node);
}
}
// Where outerHTML supported
else if ( existing_node.o uterHTML ) {
existing_node.o uterHTML = A;
}
}

/*
Pure DOM - createElement and add the text,
then replace the old node
*/
function newElement( oid, tag, nid, txt ) {
var oNode = document.getEle mentById( oid );
var nNode = document.create Element( tag );
nNode.id = nid;
nNode.appendChi ld(document.cre ateTextNode( txt ));
oNode.parentNod e.replaceChild( nNode, oNode);
}
</script>
</head>
<body>

<div id="yy">
<h2>here is one</h2>
<h2 id="zz">Now is
<script type="text/javascript">
document.write( timeNow() );
</script></h2>
</div>
<div style="backgrou nd-color: #ddffdd; border: 1px solid green;">
<input type="button" value="add/remove div" onclick="
divMethod();
">
<input type="button" value="createCo ntextualFragmen t/outerHTML" onclick="
pseudoOuterHTML ();
">
<input type="button" value="createEl ement" onclick="
newElement( 'zz', 'h2', 'zz', 'Now is ' + timeNow() );
">
</div>

</body>
</html>
--
Rob
Jul 23 '05 #7

In short, IE doesn't seem to allow such changes for TRs. So, I used
insertRow and insertCell in the table. Then I changed the innerHTML of
the cell to the string in my variable. This slightly changed the way
the link was displayed in Mozilla, however. So, i still use replace
node and innerHTML for mozilla users.

Thanks a lot for your help

Anand
--
Anand
------------------------------------------------------------------------
Anand's Profile: http://www.highdots.com/forums/member.php?userid=72
View this thread: http://www.highdots.com/forums/showthread.php?t=1746467

Jul 23 '05 #8
Anand wrote:
In short, IE doesn't seem to allow such changes for TRs. So, I used
insertRow and insertCell in the table. Then I changed the innerHTML of
the cell to the string in my variable. This slightly changed the way
the link was displayed in Mozilla, however. So, i still use replace
node and innerHTML for mozilla users.

Thanks a lot for your help
That sounds pretty nasty. If you use standard DOM methods such as:

var newRow = document.create Element('TR');
var newCell = document.create Element('TD');

and replace existing rows & cells with them, you will have code that
works in *both* IE and Mozilla without needing to differentiate at all
(though you should test that createElement is supported for general
compatibility). You should also replace rows based on the tbody
element, not the table (IE refuses to do anything if you try to add rows
to the table element). This is quite easy if you know the row you want
to replace by using:

rowToReplace.pa rentNode.replac eChild(newRow, rowToReplace);

You can then use innerHTML to replace the contents of the cell, as you
are currently doing (though as noted that will fail in some browsers,
but no more frequently than your method above).


Anand

--
Rob
Jul 23 '05 #9

Hello Rob,
The method I happened to implement finally does work for both IE
and Mozilla. Mozilla/Firefox however showed slight spacing problem
(extra line and not starting from right most end as other links) when
they were being replaced. Thas is the only reason I had different codes
for these two browsers. I wouldn't be surprised if I am doing them by
myself for some reason unknown to me yet.

IE did not refuse to add rows in table element. I could add a row
by using insertRow to a table object (got by getElementById( mytable)).
In addition to adding a row, I add a cell in the row again by using
myrow.insertCel l. Then the Cell's innerHTML is changed to my string.
This worked fine for me.

As I mentioned earlier, replaceChild after createElement only
managed to give me 'space' instead of newnode. I am still unaway why
that would happen!!!

I also read in another web forum that using innerHTML for TRs and TDs
is not supported by IE.

Anand
--
Anand
------------------------------------------------------------------------
Anand's Profile: http://www.highdots.com/forums/member.php?userid=72
View this thread: http://www.highdots.com/forums/showthread.php?t=1746467

Jul 23 '05 #10

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

Similar topics

2
1603
by: Horny Porno-thologist | last post by:
Dear everyone, I managed to get most of my code (nesting documents etc.) worked out, but there are a few niggles. The first one is as follows: My first document is: <?xml version="1.0" encoding="UTF-8" standalone="yes"?> <WfMessage>
1
11313
by: Chi | last post by:
Hi There, The following is a popup form that works exactly as I want but I now need to get the values of each text box added when a user clicks the 'Add' button and pass the values back the opener form into a textarea. Thanks in advance! ================================ CODE BELOW
4
150496
by: Michael Hill | last post by:
I have this tag: <span id="member_id"></span> and I want to change the value to "Member" why can't I do: document.getElementByID("member_id").value = "Member";
1
2318
by: Thomas | last post by:
Hy dudes, I have a strange problem. I dynamically create an IFrame with JavaScript and then fill in some content. Afterwards I want to switch to designMode. There the trouble starts. In Mozilla it works perfectly (even it doesn't stop loading the page, but this doesn't matter), but the whole IE crashes and shuts down itself without reason. Can you help? Has someone had the same problem? I already switched the order for filling the...
3
1662
by: Christopher Benson-Manica | last post by:
I need a simple HTML element whose text I can change dynamically. What is it? (it doesn't seem to be <div>, since I can't seem to find what properties a <div> has...) -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
4
2484
by: Lukasz Indyk | last post by:
hello;) i have a piece of html code, and want to replace every image on my page with this code. now i do it by replacing IMG node with SPAN node, and then setting innerHTML property of SPAN node with my html code: var nodeToReplaceWith = document.createElement("<SPAN>"); nodeToReplaceWith.innerHTML = HTMLCodeToReplaceWith; node.replaceNode(nodeToReplaceWith);
16
13335
by: Joel Byrd | last post by:
I am having this ridiculous problem of trying to set the innerHTML of a div node. It works in all other browsers, but internet explorer is giving me an "Unknown runtime error". This is actually in the context of developing an auto-suggest (basically reverse-engineering Google Suggest), but I don't see how any of the other code has anything to do with it. I *pretty sure* that I've narrowed it down to 1 line (the line on which the...
6
7252
by: Adam Tilghman | last post by:
Hi all, I have found that IE doesn't seem to respect the <SELECT> "multiple" attribute when set using DOM methods, although the attribute/property seems to exist and is updated properly. Those changes just don't make it onto the screen. Am I doing something wrong here? If not, is there a better feature test I can use than "appName.match()"?
22
5367
by: delraydog | last post by:
It's quite simple to walk to the DOM tree going forward however I can't figure out a nice clean way to walk the DOM tree in reverse. Checking previousSibling is not sufficient as the previousSibling could be a node which has childNodes and therefore the 'true' previousSibling would be the *deepest* lastChild of the previousSibling... For example, given this graph: 1 myAnchor nodeType 1 2 myAnchorText1 nodeType 3
0
8385
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8303
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
8821
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
8723
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...
0
5632
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
4150
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
4300
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2726
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
1941
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.