473,396 Members | 1,942 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.

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.createElement("H2");
newnode.innerHTML = A;
oldnode.replaceChild(newnode,existing_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 7101
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.createElement("H2");
newnode.innerHTML = A;
oldnode.replaceChild(newnode,existing_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.createElement("H2");
newnode.appendChild(document.createTextNode(A));
oldnode.replaceChild(newnode,existing_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.com.au/group/comp.lang.javascript/browse_thread/thread/8acbf8295c3cedc9/0efaa271ed564bfb?q=view+source+code+javascript+inn erHTML&rnum=1&hl=en#0efaa271ed564bfb>

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.write("<FORM NAME=\"SPAM\"><TEXTAREA NAME=\"SRC\"
ROWS=45 COLS=82></TEXTAREA></FORM>");
CODE.document.SPAM.SRC.value=document.documentElem ent.innerHTML; 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.createElement("H2");
newnode.appendChild(document.createTextNode(A));
oldnode.replaceChild(newnode,existing_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.createElement("H2");
newnode.appendChild(document.createTextNode(A));
oldnode.replaceChild(newnode,existing_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.innerHTML = 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 createDocumentFragment:

<URL:http://www.mozilla.org/docs/dom/domref/dom_doc_ref45.html#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 createDocumentFragment:

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

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


createDocumentFragment 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.getElementById('yy');
var existing_node = document.getElementById('zz');

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

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

// Add it to the document
document.body.appendChild(tNode);

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

// Clone the node that was created
var xNode = tNode.firstChild.cloneNode(true);

// Replace 'existing_node' with the new cloned node
existing_node.parentNode.replaceChild(xNode, existing_node);

// Delete the temp div and its content
tNode.parentNode.removeChild(tNode);

">

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'>Question 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.innerHTML = A;
parent.replaceChild(newnode,existing_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.com/forums/attachment.php?attachmentid=156|
+-------------------------------------------------------------------+

--
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.firstChild.cloneNode(true);
xNode.style.display = '';

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'>Question 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.innerHTML = A;
parent.replaceChild(newnode,existing_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 createContextualFragment, 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>outerHTML 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.getMinutes())
+ ':' + preZ(t.getSeconds())
t = t*1 + '';
s += '.' + t.substring(t.length-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.getElementById('yy');
var existing_node = document.getElementById('zz');

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

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

// Add it to the document
document.body.appendChild(tNode);

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

// Clone the node that was created
var xNode = tNode.firstChild.cloneNode(true);
xNode.style.display = '';

// Replace 'existing_node' with the new cloned node
existing_node.parentNode.replaceChild(xNode, existing_node);

// Delete the temp div and its content
tNode.parentNode.removeChild(tNode);
}

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

// if ( existing_node.ownerDocument.createRange ) {
if ( document.createRange ) {

// Where createRange supported
var r = document.createRange();
r.selectNode(existing_node);

// And createContextualFragment supported
// It's a Mozilla extension...
if ( r.createContextualFragment ) {
var frag = r.createContextualFragment(A);
existing_node.parentNode.replaceChild(frag, existing_node);
}
}
// Where outerHTML supported
else if ( existing_node.outerHTML ) {
existing_node.outerHTML = A;
}
}

/*
Pure DOM - createElement and add the text,
then replace the old node
*/
function newElement( oid, tag, nid, txt ) {
var oNode = document.getElementById( oid );
var nNode = document.createElement( tag );
nNode.id = nid;
nNode.appendChild(document.createTextNode( txt ));
oNode.parentNode.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="background-color: #ddffdd; border: 1px solid green;">
<input type="button" value="add/remove div" onclick="
divMethod();
">
<input type="button" value="createContextualFragment/outerHTML" onclick="
pseudoOuterHTML();
">
<input type="button" value="createElement" 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.createElement('TR');
var newCell = document.createElement('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.parentNode.replaceChild(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.insertCell. 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
JRS: In article <P1******************@news.optus.net.au>, dated Tue, 12
Jul 2005 01:29:19, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.auau> posted :
function preZ( x ) {
return ( 10 > x )? '0' + x : x;
}


Note that the function returns sometimes a String and sometimes a
Number, and is unsatisfactory for x<0. However, it's good on NaN,
better than what I currently use.

It will be entirely satisfactory for the intended purpose; but I'm still
somewhat unhappy about more general use, in which there may be a
significant chance, during development, of the input value being outside
0..99.
How about function nLZ(x) { return (x>=0&&x<10?"0":"") + x } // ??

--
© 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 #11

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

Similar topics

2
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"...
1
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...
4
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
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...
3
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...
4
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...
16
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...
6
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...
22
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...
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
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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...
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
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...
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,...

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.