473,705 Members | 3,580 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

appendChild(), remove Child()

Ken
I am trying to create one image using JavaScript; then later in the script
remove the image - not just remove the src.
The following creates the image, but I have been unable to remove it.

How do I structure
document.getEle mentById('num1' ).removeChild(i mage_display); ?

<input type=file name="picture1" onChange="image (this.value, 'num1');"
Id="pt1">
<div id='num1'></div>

<script type="text/javascript">
function image_size(fiel d, num){
image_display=d ocument.createE lement('img');
image_display.s rc=field;
document.getEle mentById('num1' ).appendChild(i mage_display);
..
..
..
document.getEle mentById('num1' ).removeChild(i mage_display);
}
</script>

Thanks for help.

Ken
Jul 23 '05 #1
9 36998
Ken wrote:
I am trying to create one image using JavaScript; then later in the script
remove the image - not just remove the src.
The following creates the image, but I have been unable to remove it.

How do I structure
document.getEle mentById('num1' ).removeChild(i mage_display); ?

<input type=file name="picture1" onChange="image (this.value, 'num1');"
Id="pt1">
<div id='num1'></div>

<script type="text/javascript">
function image_size(fiel d, num){
image_display=d ocument.createE lement('img');
You should at least test if "field" has a value:

if (field != '') {
....

If the user has entered some text, then cleared the text box, you will
add a broken image tag. You could test to see if it is valid file
path, but you can't determine if the file itself actually exists. You
should add a reset button so at least the user can clear the box
without creating a broken tag.

<input type="reset" value="Reset">
image_display.s rc=field;
This only works in IE (AFAIK). To make it work in other browsers (and
still keeping it working in IE), use:

image_display.s rc='file://' + field;
document.getEle mentById('num1' ).appendChild(i mage_display);
You have created image_display as a global variable. If the user adds
multiple images, each one gets the same variable name. "image_disp lay"
will only refer to the last image added (or the last image object
created, even if the file path was invalid).
document.getEle mentById('num1' ).removeChild(i mage_display);


So your remove will only remove the last one and "image_disp lay" will
reference a non-existent object. I'm not sure why the above doesn't
work (I'm sure one of the lurking experts will fill us in) but the
below code does:

image_display.p arentNode.remov eChild(image_di splay);

Note that the above tips just get your code to work (more or less),
there are lots of usability issues to deal with, such as:

- how will a user remove a specific image, not just the last one added?
- how to prevent adding a new image every time the field changes?
(hint: add a button to add the image, don't use onchange)
- if the file doesn't exist, how will you avoid a broken img tag?
- how will you control how many images a user adds to a page?

Cheers, Rob.
Jul 23 '05 #2
RobG wrote:
[snip]
add a broken image tag. You could test to see if it is valid file
path, but you can't determine if the file itself actually exists. You

[snip]

What I meant is that you can check the syntax using regex, but not
whether the path or file actually exists.

Cheers, Rob.
Jul 23 '05 #3

"Ken" <kk******@wi.rr .com> wrote in message
news:pm******** *********@twist er.rdc-kc.rr.com...
I am trying to create one image using JavaScript; then later in the script
remove the image - not just remove the src.
The following creates the image, but I have been unable to remove it.

How do I structure
document.getEle mentById('num1' ).removeChild(i mage_display); ?
You can use a DOM reference which will no longer be valid after you use it.
In the example below the first click deletes the img the next the btn.

<HTML><HEAD><TI TLE></TITLE></HEAD>
<BODY>
<img id="num1" src="my.gif">
<button
onclick="docume nt.body.removeC hild(document.b ody.childNodes[0])">Click to
remove image</button>
</BODY></HTML>

any reference that the browser can use is fine in place of
document.body.c hildNodes[0]
e.g. MS
document.body.r emoveChild(num1 );
document.body.r emoveChild(docu ment.all.num1);
e.g. MS6 and others
document.body.r emoveChild(docu ment.getElement ById('num1');
and also the tags collection but I don't remember the syntax offhand
my preference
document.body.r emoveChild(wind ow['num1']);
I think bracket reference is supported all UA's but I'm sure someone will
correct me if not.
Hope this helps.
Jimbo
<input type=file name="picture1" onChange="image (this.value, 'num1');"
Id="pt1">
<div id='num1'></div>

<script type="text/javascript">
function image_size(fiel d, num){
image_display=d ocument.createE lement('img');
image_display.s rc=field;
document.getEle mentById('num1' ).appendChild(i mage_display);
.
.
.
document.getEle mentById('num1' ).removeChild(i mage_display);
}
</script>

Thanks for help.

Ken

Jul 23 '05 #4
Ken
"Ken" <kk******@wi.rr .com> wrote in message
news:pm******** *********@twist er.rdc-kc.rr.com...
I am trying to create one image using JavaScript; then later in the script
remove the image - not just remove the src.
The following creates the image, but I have been unable to remove it.

How do I structure
document.getEle mentById('num1' ).removeChild(i mage_display); ?

<input type=file name="picture1" onChange="image (this.value, 'num1');"
Id="pt1">
<div id='num1'></div>

<script type="text/javascript">
function image_size(fiel d, num){
image_display=d ocument.createE lement('img');
image_display.s rc=field;
document.getEle mentById('num1' ).appendChild(i mage_display);
.
.
.
document.getEle mentById('num1' ).removeChild(i mage_display);
}
</script>

Thanks for help.

Ken

I have been experimenting with both approaches. The results have been
inconsistent. Sometime the approach works and other times it does not.
I have tried to display the tree associated with Id=num1 with little
results. I keep getting either undefined or [object].

How can I display the tree (parent, children, etc...tags)?
i.e.the tag <img src=field name=?? >

Ken

Jul 23 '05 #5
Ken wrote:
I have been experimenting with both approaches. The results have been
inconsistent. Sometime the approach works and other times it does not.
I have tried to display the tree associated with Id=num1 with little
results. I keep getting either undefined or [object].

How can I display the tree (parent, children, etc...tags)?
i.e.the tag <img src=field name=?? >


The solution I provided works with any browser that supports the
DOM. Your problem is reliably identifying the image the user wants to
delete. I suggest that when you add the image, add a DIV and a remove
button, then the user just clicks on the remove button next to or below
the image to remove it. You can use then use this.form.paren tNode to
get the DIV that the image is in rather than trying to remember the
name of specific images.

My method would be to use a DOM method to create a new DIV and make it
a child of your num1 div. Then I'd use innnerHTML to add the image and
remove button. The remove button would look something like:

<form action="">
<input type="button" value="Remove this image"
onclick="remove Image(this.form .parentNode)";>
</form>
The removeImage function therefore gets a reference to the div to
remove. You can then just use theDiv.parentNo de.removeChild( theDiv).

Here is a simple DOM walk that you can use. It would be much better to
use a browser that has a DOM viewer (nearly any browser other than IE),
but if you are really stuck, use the one below.

Cheers, Rob.

<html>
<head>
<title> DOM Tree </title>

<script type="text/javascript">
// shows the DOM with index
function showDOM() {
var msg = "";
function listNodes(n,x) {
msg += x + ' ' + n.nodeName
if (n.name) msg += ' name is: ' + n.name;
if (n.value) msg += ' value is: ' + n.value;
if (n.src) msg += ' src is: ' + n.src;
msg += '\n';
for (var i=0; i<n.childNodes. length; i++) {
listNodes(n.chi ldNodes[i],x + '.' + i);
}
}
listNodes(docum ent.getElements ByTagName("body ")[0],'0');
alert(msg);
}
</script>

</head>
<body>
<form action="" name="theForm">
<input type="button" value="Show DOM" name="theButton "
onclick="showDO M();">
</form>
<p>below is a broken img tag</p>
<img src="blah.gif">
</body>
</html>
Jul 23 '05 #6
Ken wrote:
"Ken" <kk******@wi.rr .com> wrote in message
I am trying to create one image using JavaScript; then later in the script
remove the image - not just remove the src.
The following creates the image, but I have been unable to remove it.
[snip]
I have been experimenting with both approaches. The results have been
inconsistent. Sometime the approach works and other times it does not.
I have tried to display the tree associated with Id=num1 with little
results. I keep getting either undefined or [object].


Below is some code to add and remove images to a page from a local file
system. Tested in IE 6 and Firefox, modify for your purpose.

If you are trying to add an image, then remove it within the one
script, I suggest you split the add and remove bits to separate
functions and call them from your main script. IE and other browsers
seem a little finicky about adding/removing items within the one script,
putting them into separate functions makes them work perfectly for me.

Rob.
<html>
<head><title>Ad d your images...</title>
<style type="text/css">
body
{font-family: arial, sans-serif;}
p
{font-size: 80%;}
div
{border-bottom: thin solid blue;
padding: 10 0 10 0;
}
</style>

<script type="text/javascript">
function addImage(p,d){
// alert(p);
if (p == '') {
alert('Please enter file path to your image,'
+ ' or use the \'Browse...\' button'
+ '\nto locate an image to add to the page, then '
+ 'click the "Add image" button');
return;
} else {
if (document.getEl ementById) {
newDiv = document.create Element('div');
document.getEle mentById(d).app endChild(newDiv )
var tagText = ''
+ '<img src="' + 'file://' + p
+ '" alt="' + p + '"><br>'
+ '<form action="">'
+ '<h3>Image path: ' + p
+ '<input type="button" style="margin-left: 20;"'
+ ' value="Click to remove image"'
+ ' onclick="remove Image(this.form .parentNode);"> '
+ '</h3>'
+ '</form>'
;
newDiv.innerHTM L = tagText;
} else {
alert('No support for getElementById. \n'
+ 'Use another method');
} } }

function removeImage(x) {
// alert(x);
x.parentNode.re moveChild(x);
}
</script>
</head>
<body>
<h2>Add images to this page</h2>
<form action="">
<p>
<label title="Choose an image to upload" for="filePath">
<span style="color: 336699;">&nbsp; File path....</span>
<br>
<input type="file" id="filePath"
name="filePath" size="60"></label>
<label title="Add an image to this page">
<input type="button" value="Add image"
onclick="addIma ge(this.form.fi lePath.value,'i mageDiv');">
</label>
<label title="Clear the file path">
<input type="reset" value="Reset"></label>
</p>
</form>
<div id="imageDiv"
style="border-top: thin solid blue; border-bottom: none;"></div>
</body>
</html>
Jul 23 '05 #7
Ken
"RobG" <rg***@iinet.ne t.auau> wrote in message
news:tU******** *********@news. optus.net.au...
Ken wrote:
I have been experimenting with both approaches. The results have been
inconsistent. Sometime the approach works and other times it does not.
I have tried to display the tree associated with Id=num1 with little
results. I keep getting either undefined or [object].

How can I display the tree (parent, children, etc...tags)?
i.e.the tag <img src=field name=?? >


The solution I provided works with any browser that supports the
DOM. Your problem is reliably identifying the image the user wants to
delete. I suggest that when you add the image, add a DIV and a remove
button, then the user just clicks on the remove button next to or below
the image to remove it. You can use then use this.form.paren tNode to
get the DIV that the image is in rather than trying to remember the
name of specific images.

My method would be to use a DOM method to create a new DIV and make it
a child of your num1 div. Then I'd use innnerHTML to add the image and
remove button. The remove button would look something like:

<form action="">
<input type="button" value="Remove this image"
onclick="remove Image(this.form .parentNode)";>
</form>
The removeImage function therefore gets a reference to the div to
remove. You can then just use theDiv.parentNo de.removeChild( theDiv).

Here is a simple DOM walk that you can use. It would be much better to
use a browser that has a DOM viewer (nearly any browser other than IE),
but if you are really stuck, use the one below.

Cheers, Rob.

<html>
<head>
<title> DOM Tree </title>

<script type="text/javascript">
// shows the DOM with index
function showDOM() {
var msg = "";
function listNodes(n,x) {
msg += x + ' ' + n.nodeName
if (n.name) msg += ' name is: ' + n.name;
if (n.value) msg += ' value is: ' + n.value;
if (n.src) msg += ' src is: ' + n.src;
msg += '\n';
for (var i=0; i<n.childNodes. length; i++) {
listNodes(n.chi ldNodes[i],x + '.' + i);
}
}
listNodes(docum ent.getElements ByTagName("body ")[0],'0');
alert(msg);
}
</script>

</head>
<body>
<form action="" name="theForm">
<input type="button" value="Show DOM" name="theButton "
onclick="showDO M();">
</form>
<p>below is a broken img tag</p>
<img src="blah.gif">
</body>

Rob,
Thanks for the DOM tree script. It is a big help to see the parent, child,
etc relationsionshi ps.

I now have the add and remove image working. I would appreciate your
comments on three questions:
1. Over the various browsers, is it better to use:
document.getEle mentById('num1' ).removeChild(i mage_display);
or
image_display.p arentNode.remov eChild(image_di splay);

2. Do most of the newer version browsers (Mozilla, IE, Firefox, etc)
accept the above scripts?

3. I would like to measure the fileSize of the image. I use:
var size_pic = document.getEle mentById('num1' ).childNodes[0].fileSize;
alert("size = " + size_pic);
which works with one exception.

With a first time displayed image, the first time the script displays a size
= -1 The image is displayed on the first pass. The fileSize script is
after the image is img script.
The second pass is correct. size = 11479

Is this a cache problem? The first pass caches the file, the second pass
reads the file?
I tried running - var size_pic =
document.getEle mentById('num1' ).childNodes[0].fileSize; - twice but that
made no difference.

Is there a work around for this problem.

Is there a better way to measure filesize in JavaScript?

Have a good day!

Ken
Jul 23 '05 #8
Ken wrote:
[snip]
I now have the add and remove image working. I would appreciate your
comments on three questions:
1. Over the various browsers, is it better to use:
document.getEle mentById('num1' ).removeChild(i mage_display);
or
image_display.p arentNode.remov eChild(image_di splay);

I'm certainly no expert on either JavaScript or the DOM, so if Mike
Winter or one of the other gurus is lurking, I'd love to hear their
opinion. If they don't post in a day or so, create a new post and ask
the question there.

My opinion is that if you pass a reference to the object (as I've done
in the working example) you don't need to use getElementById, which is
reasonably new, and therefore likely to be more widely compatible. So
I guess that makes the parentNode method 'better'. It also means you
aren't using a hard coded reference to an element ID ('num1') - though
you are using it to add the image in the first place, so perhaps it's a
moot point.

Since you already have a reference in 'image_display' , I don't see the
point in using getElementById a second time.
2. Do most of the newer version browsers (Mozilla, IE, Firefox, etc)
accept the above scripts?
Yes. I usually test in IE 6, Mozilla, Firefox, Netscape, Safari and
don't have any issues with DOM or document node stuff. BUT I don't
develop for the web like many here do so my opinion is not particularly
useful. I develop intranet applications and my interest in
cross-platform compatibility is more for philosophical motives than
practical necessity.

Generally speaking, if you work in Firefox and test in IE you will do
OK. Mozilla, Netscape and Firefox are so similar as to be nearly the
same (but not quite), Safari is pretty similar too but it is a tad
immature (particularly as you have to buy OS X upgrades to get the
latest version, so many Mac users don't have it).

3. I would like to measure the fileSize of the image. I use:
var size_pic = document.getEle mentById('num1' ).childNodes[0].fileSize;
alert("size = " + size_pic);
which works with one exception.


Beyond my knowledge, I'm afraid. If you don't get an answer in a day
or so, post it as a new thread.

Cheers, Rob.
Jul 23 '05 #9
Ken wrote:
[snip]

Is there a better way to measure filesize in JavaScript?


I decided to have a play, and found the following:

1.
On Windows -
When adding a file using an input type="file", you must add "file://"
to the front of the path returned by the file dialog or Firefox on
Windows will not find the path. Prepending "file://" works in IE on
Windows too, but is not needed, you can just use the path returned by
the dialog.

On Mac -
"file://" works with Safari, Camino, Firefox but not IE

"" (don't add anything) works with all the above but not IE

"file:/" (just one slash) works in IE only - go figure. IE kept
crashing too, not a good sign.

This may be a legitimate excuse for browser detection - I'd probably go
for "file://" and try to detect IE on Mac and do "file:/".

2.
When adding the image, IE adds a full set of attributes but doesn't
give them values unless you add them yourself. All the other browsers
only add the attributes that you give the image yourself, so IE has a
big list of empty attributes (even height and width are empty) and the
others have a short list of just the ones you added (src + alt in my
example).

So there is no way of getting the file size or height/width in any
browser I tested - you can likely do it in IE on Windows only (there
was a recent thread on this and I think that was the consensus).

Cheers, Rob.
Jul 23 '05 #10

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

Similar topics

25
5186
by: kie | last post by:
hello, i have a table that creates and deletes rows dynamically using createElement, appendChild, removeChild. when i have added the required amount of rows and input my data, i would like to calculate the totals in each row. when i try however, i receive the error: "Error: 'elements' is null or not an object"
2
10852
by: samuel.adam | last post by:
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;
7
3143
by: Robert Oschler | last post by:
I'm having a very painful time converting some Mozilla dynamic DOM code to work with Internet Explore. For example, given this code: -------------- selectBox=document.createElement("SELECT"); selectBox.name="theSelectBox"; optionOne=document.createElement("OPTION"); optionOne.name="option1"; optionOne.value="one";
2
3441
by: Marco | last post by:
Hello! Can anyone explain why the following code does not work? (I'm using python2.4.) Cheers, Marco --
3
2306
by: anonymous | last post by:
Can you not append a XmlWhiteSpace node to XmlDocument? See example: using System; using System.Xml; class TestXml { public static void Main(string args)
1
1134
by: beanweed | last post by:
This is a problem with a ASP.NET application I am writing. The interface allows a user to manipulate an XML document. I have in my xmldocument .. . . <item id="1"> <parents /> <label>item1</label> </item> <item id="3">
2
1438
by: sicapitan | last post by:
The appendChild to the row_container works a treat, while column_container remainds blank, and it appears at the bottom of my document Hmm, here is my code : function initGrid() { row_id = 1;
1
1333
by: Sek | last post by:
Hi Folks, I have come across a behaviour which seems strange to me. I wrote the following code for a task: -----BEGIN CODE------- XmlDocument idc = new XmlDocument(); idc.LoadXml("<book><title>The Confidence Man</title><first-name>Herman</first-name><last-name>Melville</last-name></book>");
2
3770
by: GuruPrasadBytes | last post by:
I am opened window.open(child.aspx page) from the parent.aspx file the below code is from parent.aspx, <HTML> <HEAD> ...... </HEAD> <body onload="loadXML();"> ..... <input id="AddSecurityBtn" type="button" runat="server" onclick='javascript: Args = objDoc.selectSingleNode('//Books'); Args = buildBookTable ; Args =null; window.open('child.aspx','800','900');' value="Add Books" />
0
8689
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
9273
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
9136
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
9030
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
7893
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
5933
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
4439
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
4703
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
2081
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.