469,647 Members | 1,794 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,647 developers. It's quick & easy.

getElementById problem with Firefox

I have the following problem:
I populate a page with a specific amount of <div id="MyTest"> containers inside another <div> container.

for (i=0; i < MyString.length; i++)
document.write('<div id="MyTest"
style="position:absolute;top:0px;left:0;height:12; width:12;text-align:center">'+MyString[i]+'</div>');

Now if MyString contains 6 characters, I end up with 6 <div id="MyTest"> containers.

With IE I am able to access these containers as follows:

for (i=0; i < MyString.length; i++) {
var Obj=MyTest[i].style;
Obj.top=NewPositionTop;
Obj.left=NewPositionLeft+i;
}

Now with Firefox this didn't work
Javascript Error: file:///c:/test/mytest.js, line 209: MyTest[i] has no properties

and the Javascript Console suggests:
Warning: Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.

so I decided to use getElementById(), but keep getting errors.
I tried:
Obj1=document.getElementById("MyTest");
and then access Obj1[i].style.top/left but

Javascript Error: file:///c:/test/mytest.js, line 210: Obj1[i] has no properties

I also tried Obj=document.getElementById("MyTest")[i].style;

with the same result.

What is it that keeps me from accessing a specific entry in the getElementById("MyTest") list/array?

can anyone point me in the right direction?

Thanks, Robi

Jul 23 '05 #1
24 9663
On 13/07/2005 15:00, Robi wrote:
I have the following problem:
I populate a page with a specific amount of <div id="MyTest"> containers inside another <div> container.
You cannot do that. An id attribute value must be unique throughout an
entire document.
for (i=0; i < MyString.length; i++)
document.write('<div id="MyTest" [...]
As you're writing each element, you can append the value of i to produce
unique values.

[snip]
With IE I am able to access these containers [using a global variable with the same name]
Yes, you can. However, this is a terrible feature in my opinion, and you
shouldn't use it.

[snip]
Obj1=document.getElementById("MyTest");
and then access Obj1[i].style.top/left but


The getElementById method returns a single element, not a collection,
because there should only ever be one element with a matching value. If
you do have multiple potential matchs, the most common result is that
first (in source order) will always be returned.

Continuing the suggestion above, you can alter your code to:

var obj = document.getElementById('MyTest' + i);

if(obj && obj.style) {
/* ... */
}

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #2
ASM
Robi wrote:
I have the following problem:
I populate a page with a specific amount of <div id="MyTest"> containers inside another <div> container.

for (i=0; i < MyString.length; i++)
document.write('<div id="MyTest"
style="position:absolute;top:0px;left:0;height:12; width:12;text-align:center">'+MyString[i]+'</div>');
it is not allowed to have more than 1 element with same ID !

so try something as :

myHtml = '';
for (i=0; i < MyString.length; i++)
myHtml += '<div id="MyTest'+i+'"'+
'style="position:absolute;top:0px;left:0;height:12 ;width:12;text-align:center">'+
MyString[i]+'</div>');
document.write(myHtml);

Would be better to have a separte css to do not copy same thing x times
With IE I am able to access these containers as follows:

for (i=0; i < MyString.length; i++) {
var Obj=MyTest[i].style;
Obj.top=NewPositionTop;
Obj.left=NewPositionLeft+i;
}


yes that's IE way of work

try :
for (i=0; i < MyString.length; i++) {
var Obj = document.all?
MyTest[i].style :
document.getElementById?
document.getElementById('MyTest'+i).style :
document.layers['MyTest'+i] ;
Obj.top = NewPositionTop+'px';
Obj.left = NewPositionLeft+'px';
}

Notice that document.write()
is not an "up to date" way to script
See : createElement and appendChild
See also : cloneNode (ask to google)

--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #3
Michael Winter wrote:
On 13/07/2005 15:00, Robi wrote:
I have the following problem:
I populate a page with a specific amount of <div id="MyTest"> containers
inside another <div> container.


You cannot do that. An id attribute value must be unique throughout an
entire document.
for (i=0; i < MyString.length; i++)
document.write('<div id="MyTest" [...]


As you're writing each element, you can append the value of i to produce
unique values.

[snip]
With IE I am able to access these containers [using a global variable with the same name]


Yes, you can. However, this is a terrible feature in my opinion, and you
shouldn't use it.


Thanks, will avoid/omit the use of it from now on.
Obj1=document.getElementById("MyTest");
and then access Obj1[i].style.top/left but


The getElementById method returns a single element, not a collection,
because there should only ever be one element with a matching value. If
you do have multiple potential matchs, the most common result is that
first (in source order) will always be returned.

Continuing the suggestion above, you can alter your code to:

var obj = document.getElementById('MyTest' + i);

if(obj && obj.style) {
/* ... */
}


well, I did "forget" to mention in my post, that that was the /workaround/
I used.
The script was written by someone else and I was trying to adapt it to work
at least in my browser as well. Somehow I did know that element IDs should
be unique in a document although when I saw this code I thought it was a
neat way to access the objects.

Thanks for your reply and for getting me out of my doubt if I had done it
correctly or not.

What I don't understand is why do you check for (obj && obj.style).
Wouldn't a check for just (obj.style) suffice? Besides, since I know I set
the style, wouldn't (obj) be enough?

Robi
Jul 23 '05 #4
ASM wrote:
Robi wrote:
I have the following problem:
I populate a page with a specific amount of <div id="MyTest"> containers inside another <div> container.

for (i=0; i < MyString.length; i++)
document.write('<div id="MyTest"
style="position:absolute;top:0px;left:0;height:12; width:12;text-align:center">'+MyString[i]+'</div>');
it is not allowed to have more than 1 element with same ID !

except for IE ;-) , but then, Microsoft has always been special ;-)
so try something as :

myHtml = '';
for (i=0; i < MyString.length; i++)
myHtml += '<div id="MyTest'+i+'"'+
'style="position:absolute;top:0px;left:0;height:12 ;width:12;text-align:center">'+
MyString[i]+'</div>');
document.write(myHtml);

Would be better to have a separte css to do not copy same thing x times
Thanks, I'll keep that in mind
With IE I am able to access these containers as follows:

for (i=0; i < MyString.length; i++) {
var Obj=MyTest[i].style;
Obj.top=NewPositionTop;
Obj.left=NewPositionLeft+i;
}


yes that's IE way of work

try :
for (i=0; i < MyString.length; i++) {
var Obj = document.all?

^^^^^^^^^^^^
[undefined] in my tests

I came up with
NS4=(document.layers)?1:0;
IE4=(document.all)?1:0;
W3C=(document.getElementById&&!document.all)?1:0;

MyTest[i].style :
document.getElementById?
document.getElementById('MyTest'+i).style :
document.layers['MyTest'+i] ;
Obj.top = NewPositionTop+'px'; ^^^^
will need to keep this in mind too
Obj.left = NewPositionLeft+'px';
}

Notice that document.write()
is not an "up to date" way to script
See : createElement and appendChild
See also : cloneNode (ask to google)


as well as these :-)
Merci

Robi
Jul 23 '05 #5
On 13/07/2005 19:26, Robi wrote:
Michael Winter wrote:
[snip]
var obj = document.getElementById('MyTest' + i);

if(obj && obj.style) {
/* ... */
}


[snip]
What I don't understand is why do you check for (obj && obj.style).
Wouldn't a check for just (obj.style) suffice?
If the call didn't succeed, obj will be null and trying to access a
property will cause the script to error out.

For instance, my version of Konqueror implements the
ViewCSS.getComputedStyle method, however it always returns null. You
should always check return values unless a method guarantees success, or
perhaps if you're in an environment where you can make certain
assumptions about which browsers are in use.
Besides, since I know I set the style, wouldn't (obj) be enough?
You're assuming that style property is supported. That isn't a safe bet
on the Web, at least.

In a similar fashion, you should check that the getElementById method is
supported before calling it. This style of defensive programming is
termed feature detection, where one examines the environment for support
of methods and properties before one goes about using them.
On 13/07/2005 19:39, Robi wrote:

[snip]
I came up with
NS4=(document.layers)?1:0;
IE4=(document.all)?1:0;
W3C=(document.getElementById&&!document.all)?1:0;


That is flawed. For instance, OmniWeb and Escape support the layers
collection. Similarly, OmniWeb, Opera, Konqueror, and Safari support the
all collection. Finally, just because a browser implements the
getElementById method doesn't mean it properly supports the W3C DOM.

Object inference (and browser detection in general) is not reliable and
doesn't actually tell you what you need to know: is a browser capable of
doing what I want it to?
As far as making object retrieval it's better to perform any tests once:

var getReferenceById = isGenericObject(document.getElementById)
? function(id) {
return document.getElementById(id);
}
: isObject(document.all)
? function(id) {
var result = document.all[id];

if(result) {
if(isGenericObject(result.item)) {
for(var i = 0,
n = result.length;
i < n;
++i)
{
if(id == result[i].id) {
return result[i];
}
}
} else if(id == result.id) {
return result;
}
}
return null;
}
: function() {return null;};

function isGenericObject(o) {
return isObject(o) || ('function' == typeof o);
}
function isObject(o) {
return 'object' == typeof o;
}

If you really want to bother supporting an obsolete browser like NN4,
you can follow the same pattern to add use of the layers collection.

[snip]

Hope that helps,
Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #6
ASM
Robi wrote:
ASM wrote:

it is not allowed to have more than 1 element with same ID !
Robi wrote:


except for IE ;-) , but then, Microsoft has always been special ;-)


Oh! any browser would be glad with what you want in ID :-)
clean JavaScript less, and W3C more less again

try :
for (i=0; i < MyString.length; i++) {
var Obj = document.all?


^^^^^^^^^^^^
[undefined] in my tests


Arrgghh ! :-(
I came up with
NS4=(document.layers)?1:0;
IE4=(document.all)?1:0;
W3C=(document.getElementById&&!document.all)?1:0;


why not.
See : createElement and appendChild
See also : cloneNode (ask to google)

as well as these :-)


yeap !
but
was if you'ld like to learn few more about DOM :-)
(there are so much possibilities using DOM)
--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #7
ASM
Michael Winter wrote:
On 13/07/2005 19:26, Robi wrote:
Michael Winter wrote:
If the call didn't succeed, obj will be null and trying to access a
property will cause the script to error out.


DOM way functions all of them would start with
if(document.getElementById) {
to satisfy my NC4.5 :-)
Besides, since I know I set the style, wouldn't (obj) be enough?


You're assuming that style property is supported. That isn't a safe bet
on the Web, at least.


i.e. my NC4.5 :-)
In a similar fashion, you should check that the getElementById method is
supported before calling it.
Too late ! I did say it
As far as making object retrieval it's better to perform any tests once:
Keep this novel below to try it and for my archives
(script not so easy to follow)
var getReferenceById = isGenericObject(document.getElementById)
? function(id) {
return document.getElementById(id);
}
: isObject(document.all)
? function(id) {
var result = document.all[id];

if(result) {
if(isGenericObject(result.item)) {
for(var i = 0,
n = result.length;
i < n;
++i)
{
if(id == result[i].id) {
return result[i];
}
}
} else if(id == result.id) {
return result;
}
}
return null;
}
: function() {return null;};

function isGenericObject(o) {
return isObject(o) || ('function' == typeof o);
}
function isObject(o) {
return 'object' == typeof o;
}

If you really want to bother supporting an obsolete browser like NN4,
you can follow the same pattern to add use of the layers collection.


Wonderful ! there will be a 2nd season ? :-)


--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #8
Michael Winter wrote:
On 13/07/2005 19:26, Robi wrote:
[snip]
I came up with
NS4=(document.layers)?1:0;
IE4=(document.all)?1:0;
W3C=(document.getElementById&&!document.all)?1:0;


That is flawed. For instance, OmniWeb and Escape support the layers
collection. Similarly, OmniWeb, Opera, Konqueror, and Safari support the
all collection. Finally, just because a browser implements the
getElementById method doesn't mean it properly supports the W3C DOM.


Ok, this is getting nightmarish.

I have noticed going to javascript websites
i.e. http://www.webreference.com/js/colum...pendchild.html
and clicking on the "run this script" links with my Firefox 1.0 agent
to see about ASM's suggestion and see the implementations, I get
"uncaught exceptions" which worry me, because it tells me that
every single method/object needs to be checked if it is supported
or available in the agent used (mine or someone elses).

([Exception... "Not enough arguments [nslDOMHTML.TableCellElement.cloneNode]" nsresult: "0x80570001
(NS_ERRORNS_ERROR_XPC_NOT_ENOUGH_ARGS)")

ergo, as you say:
Object inference (and browser detection in general) is not reliable and
doesn't actually tell you what you need to know: is a browser capable of
doing what I want it to?
and further:
As far as making object retrieval it's better to perform any tests once:

var getReferenceById = isGenericObject(document.getElementById)
? function(id) {
return document.getElementById(id);
}
: isObject(document.all)
? function(id) {
var result = document.all[id];

if(result) {
if(isGenericObject(result.item)) {
for(var i = 0,
n = result.length;
i < n;
++i)
{
if(id == result[i].id) {
return result[i];
}
}
} else if(id == result.id) {
return result;
}
}
return null;
}
: function() {return null;};

function isGenericObject(o) {
return isObject(o) || ('function' == typeof o);
}
function isObject(o) {
return 'object' == typeof o;
}

If you really want to bother supporting an obsolete browser like NN4,
you can follow the same pattern to add use of the layers collection.


Is there any sense in scripting at all? I mean, there's so many agents
supporting different methods, different objects, and those differently
alltogether that you'd need a whole script library for even the simplest
scripts.

Even websites, which should be able to handle this - since they "teach"
others how to do it - can't, as the above link shows.

Jul 23 '05 #9
ASM
Robi wrote:
Michael Winter wrote:
On 13/07/2005 19:26, Robi wrote:
I have noticed going to javascript websites
i.e. http://www.webreference.com/js/colum...pendchild.html


You didn't begin with a very easy tutorial
and clicking on the "run this script" links with my Firefox 1.0 agent
to see about ASM's suggestion and see the implementations, I get
"uncaught exceptions" which worry me, because it tells me that
every single method/object needs to be checked if it is supported
or available in the agent used (mine or someone elses).

([Exception... "Not enough arguments [nslDOMHTML.TableCellElement.cloneNode]" nsresult: "0x80570001
(NS_ERRORNS_ERROR_XPC_NOT_ENOUGH_ARGS)")


RhhhAaaaa ! les coquins !
Tey did forget 'true' everywhere here :
cloneNode()
->
cloneNode(true)

their last test page runs fine with this correction ( FF 1.04 Mac)
http://www.mozilla.org/docs/dom/domr..._shortTOC.html

--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #10
Robi wrote:
Michael Winter wrote: <snip>
Object inference (and browser detection in general) is
not reliable and doesn't actually tell you what you need
to know: is a browser capable of doing what I want it to?


and further:
As far as making object retrieval it's better to perform
any tests once:

<snip> Is there any sense in scripting at all?
People climb mountains, I see no sense in that, yet still they are
climbed. There is a challenge in trying to learn to do something that is
not easy, a sense of achievement from doing what is not easy and
hopefully doing it well.
I mean, there's so many agents supporting different
methods, different objects, and those differently
alltogether that you'd need a whole script library
for even the simplest scripts.
One of the most important considerations in cross-browser scripting is
that some UAs do not support scripting at all, and those that do all
allow it to be disabled. This is not a situation that can be addressed
with scripting as such, but rather script/page/system design. What is
known as 'clean degradation', which does not mean 'silent failure' but
rather that whatever is presented to the user in the face of the absence
of client-side scripting, and/or the inability of the user agent to
provide the facilities that the script requires, still provides the
required content and acceptable functionality to the user.

Having designed for clean degradation it becomes less important to bend
over backwards to actively support old and unusual browsers because, so
long as the script performs proper feature detection so that it knows
when it will need to cleanly degrade (elects not to attempt to act), the
user will be getting access to the required content and acceptable
functionality. This means that it is quite acceptable to only provide
actively scripted enhancements for W3C DOM compliant browsers and (in so
far as it is not quite W3C DOM compliant) IE (for commercial reasons).
Thus the amount of script needed (and particularly the amount of code
branching) does not need to be too great. And, well designed, much of
what is written becomes easily re-usable.

Mike's getElementById emulation being an obvious example of a re-usable
component. It benefits from the realisation that the retrieval of a
reference to a DOM element is a common task. Other obviously common
tasks that require some degree of variation between different browsers
can similarly be encapsulated into functions, objects and/or components
for easy re-use. Leaving the majority of the task of programming
eventually operating at a level above the detail of the individual
browsers.

However, be cautious of monolithic DHTML libraries as you don't want
users to be downloading large chunks of code some of which they will
never be executing, and DHTML libraries are rarely written with clean
degradation in mind.
Even websites, which should be able to handle this -
since they "teach" others how to do it - can't, as
the above link shows.


It is very easy for individuals to create web pages purporting to teach
people about browser scripting. There is just nothing to stop them, so
if they don't know the issues, don't recognise or accept the issues, or
just cannot be bothered, the results will not be of much use to those
interested in cross-browser scripting.

Anyone can claim to "teach", even without experience or knowledge. Don't
trust anything just because it is in a web page (or, for that matter, a
book on browser scripting).

Richard.
Jul 23 '05 #11
JRS: In article <f9********************@trueband.net>, dated Wed, 13
Jul 2005 13:39:23, seen in news:comp.lang.javascript, Robi
<me@privacy.net> posted :

IE4=(document.all)?1:0;


Probably not a sensible thing to do - see FAQ - but

IE4 = !!document.all

gives the same more simply.

--
© 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 #12
>> Notice that document.write()
is not an "up to date" way to script
See : createElement and appendChild
See also : cloneNode (ask to google)


Ok, so far I've been "messing" around with
document.createElement(str tag)
document.createTextNode(str value)
and so on, and now, I have questions about the amount of options:
Id=documentCreateAttribute('id'); id.value='div1'; Div1=setAttributeNode(id);
versus
Div1=setAttribute('id','div1');
versus
Div1.id='div1';

which one is "better"?

I also have another problem which I've been trying to solve:
I can't get hold of the "body" object.
It is there in the document, but whatever I do, I always end up with the error:
Body has no properties
or
Body.item(0) has no properties

here's an excerpt of my monster:
//var Body=(document.getElementsByTagName)?document.getE lementsByTagName("body").item(0):document.body;
//var Div0=Body.appendChild(document.createElement("div" ));
// above didn't work
var Body=(document.getElementsByTagName)?document.getE lementsByTagName("body"):document.body;
var Div0=Body.item(0).appendChild(document.createEleme nt("div"));
// and neither did these
Div0.id=BaseId; Div0.style.position='absolute';
Div0.style.top='0px'; Div0.style.left='0px';
var Div1=Div0.appendChild(document.createElement("div" )); Div1.style.position='relative';

the appendChild() method seems to be the culprit.

quest ce que c'est?

Robi "psycho chicken"
Jul 23 '05 #13
ASM
Robi wrote:
Notice that document.write()
is not an "up to date" way to script
See : createElement and appendChild
See also : cloneNode (ask to google)


Ok, so far I've been "messing" around with
document.createElement(str tag)
document.createTextNode(str value)
and so on, and now, I have questions about the amount of options:


Wasn't it a good idea to go to see this profusion ? :-)
Id=documentCreateAttribute('id'); id.value='div1'; Div1=setAttributeNode(id);
on my idea :
foo = document.CreateAttribute('id')
is to create an attribute nammed 'foo',
'foo' then to be use where you want by setAttributeNode.
You can start creating an element
(usualy a tag as DIV or P but could bee a child of a tag as some text)

so in the document (virtual html code of page)
1) you create an element : createElement(tag)
2) you create a text : createTextNode(text)
3) you create an attribute : createAttribute(attribute)
3b) you create the meaning of this attribute : nodeValue = string;

stil this moment we have bits of virtual code sowed somewhere in
computer mind

All what that for ?
to easily (?!) use and re-use them
to be compatible with XLM HXML
to get dynamism (without run to server and back)

So, on next step : we have to organise them
i.e : to give an aign to each td of page
foo = document.createAttribute('style');
foo.nodeValue = "right";
T = document.getElementsByTagName('TD');
for(var i=0;i<T.length;i++) T[i].setAttributeNode('foo');

That was a simple example you can modify in DOM1 ou JS as :
for(var i=0;i<T.length;i++) T[i].align='right';
or
for(var i=0;i<T.length;i++) T[i].style.textAlign='right';
but it suposes you did catch all TDs (with JS I don't know how to do)

other example :
var montitre = document.createElement("h1");
var monTexte = document.createTextNode("A very dynamical page");
montitre.appendChild(monTexte); // inserts monTexte in h1
// determine/get a space (to set the title h1)
var passagesortie = document.getElementById("here");
// place the title (just in end of the space 'passagesortie')
passagesortie.appendChild(montitre);

Try to realise this example by JS (with document.write()?)
after page has loaded -> not possible

All these commands and functions are for dynamic javascript
Some dynamism can be set with old JS (move, resize, scroll, attributes)
but not creations and/or insertions after loading

One of most interest is cloneNode
i.e.
form with a table with one row (article price quantity total button:add)
table with an id and set to hidden and non-display
table followed by a span or div whom use is contener for next insertions
and with same table (with other id and displayed and visible)
on each click on add button
hop! you clone invible table then put it in end of reserved space
(that's to say after the last table of form)
set its id, display and visible
With only a simple single table of one row you can grow your light page
to heavy and at buyer's satisfaction.

versus
Div1=setAttribute('id','div1');
versus
Div1.id='div1';

which one is "better"?
All depends ;-)
I also have another problem which I've been trying to solve:
I can't get hold of the "body" object.
mybody = document.getElementsByTagName('BODY')[0];
(1st element in tags tree of value 'body')
//var Div0=Body.appendChild(document.createElement("div" ));
supposing you'd cath body
what you wrote is : put a new div in end of body
better doing :
mybody = document.getElementsByTagName('BODY')[0];
myDiv = document.createElement("div");
to be abble to do :
for(var i=0;i<5;i++) {
myDiv = document.createElement("div");
myBody.appendChild(myDiv);
myBody.lastChild.id = 'Id_'+i;
}

the appendChild() method seems to be the culprit.

quest ce que c'est?


I don't know. What is culprit ?

c'est pour placer un element precedemment cree
that's to set an element previously created
it inserts the element just in end of space given
Like that, later, you can get it with lastChild

last example :
http://fr.selfhtml.org/javascript/ob...m#append_child
(no real english version on this site)

<html><head><title>Test</title></head>
<body>
<ol id="Liste">
<li>Element</li>
</ol>
<script language="JavaScript" type="text/javascript">
<!--
document.getElementById("Liste").removeChild(docum ent.getElementById("Liste").firstChild);

for(var i = 0; i < 10; i++) {
var newLI = document.createElement("li");
var numeroli = i + 1;
var nouveautexteli = document.createTextNode("It is list element "+
"number " + numeroli);
document.getElementById("Liste").appendChild(newLI );
document.getElementsByTagName("li")[i].appendChild(nouveautexteli);
}
//-->
</script>
</body></html>

remove the li
then create and insert 10 times : new li + new text in li

--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #14
ASM wrote:
Robi wrote: [...]
Ok, so far I've been "messing" around with
document.createElement(str tag)
document.createTextNode(str value)
and so on, and now, I have questions about the amount of options:


Wasn't it a good idea to go to see this profusion ? :-)

Grrrr! hein! mais non!
Id=documentCreateAttribute('id'); id.value='div1'; Div1=setAttributeNode(id);


on my idea :
foo = document.CreateAttribute('id')
is to create an attribute nammed 'foo',
'foo' then to be use where you want by setAttributeNode.
You can start creating an element
(usualy a tag as DIV or P but could bee a child of a tag as some text)


yeah, that is all "easy" to unnerstand, or comprendre ;) pardon my french.

[...] One of most interest is cloneNode


yep, although I can't implement it momentarily but will fool around with it too.

what I don't get is the diversity to get to the same point.
Id=documentCreateAttribute('id'); id.value='div1'; Div1=setAttributeNode(id);
versus
Div1=setAttribute('id','div1');
versus
Div1.id='div1';

which one is "better"?


All depends ;-)


I think I have reached that deep end ;-)
deep ends on what?
I also have another problem which I've been trying to solve:
I can't get hold of the "body" object.


mybody = document.getElementsByTagName('BODY')[0];
(1st element in tags tree of value 'body')


[...]
the appendChild() method seems to be the culprit.

quest ce que c'est?


I don't know. What is culprit ?


ARRRGGGHHHHHHHHHHH!!!!!!!!!!!!!!!!
this hertz!

<html>
<head>
<title></title>
<stile></style>
<script>
var Body=document.getElementsByTagName("body")[0];
Body.appendChild(document.createElement("div")); //kabloom!! because <body> is not yet created!!!!
</script>
</head>
<body>
</body>
</html>

BTW happy quartz juliet (fete d'independence la marseillaise)
Jul 23 '05 #15
ASM
Robi wrote:
ARRRGGGHHHHHHHHHHH!!!!!!!!!!!!!!!!
this hertz!

<html>
<head>
<title></title>
<stile></style>
<script>
var Body=document.getElementsByTagName("body")[0];
Body.appendChild(document.createElement("div")); //kabloom!! because <body> is not yet created!!!!
it is not *because it is DOM* that *is not javascript*

of course you have to put your commands/instructions/calls
in a right JS meanning

document.createSomethingElseWhatYouWant
I think would be put where you want (but before you call it)
(it's yet nothing more that a new object without space for it in page)

but to call an object is only possible if it exists ... (evident)
getElementsByTagName() is a function getting a specific tag tree
not to use before the tree exists
remember DOM is to manipulate existing(*) elements

(*) - html elements must be firstable read by navigator
(body ends at end of page, really exists after loading)
- existing elements can be those you did create by JS script

Body.appendChild() is a function
it calls the shortcut Body
to affect him something
(here : insert an element at end of these belonging to Body)
</script>
</head>
<body>
</body>
</html>


Want to see (with FF) a terrific code to do a simple table ?
http://perso.wanadoo.fr/stephane.mor...script-sm.html
the script is not mine it's from here :
http://www.webreference.com/js/colum...lescript5.html
where it doesn't work :-/

curiously insertion of virtual code appends fefore body last tag
(they do not use the body by its tag but by its id)

see you monday

--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #16
On 15/07/2005 00:16, Robi wrote:

[snip]
Id=documentCreateAttribute('id'); id.value='div1'; Div1=setAttributeNode(id);
versus
Div1=setAttribute('id','div1');
versus
Div1.id='div1';

which one is "better"?
The latter, in my opinion. The createAttribute method isn't supported in
IE versions prior to 6, and you'll have to make exceptions to the use of
the setAttribute method, as well.

For instance, when using the shortcut properties, one would alter the
class attribute using the className property. The name was changed
because class is a keyword in many languages (it's a future reserved
word in ECMAScript), so it's not usable with most language bindings.
However, the setAttribute method doesn't take identifiers as arguments;
it takes strings. A string literal can contain any word, keyword or not,
and indeed you should use

element.setAttribute('class', ...);

however IE is broken and still requires 'className'.
I also have another problem which I've been trying to solve:
I can't get hold of the "body" object.
When are you trying to access it? Elements are available only once
they've been parsed. Most of the time, parsing the opening tag is
sufficient, though if you're trying to interact with the contents of
that element as well, you might have to defer to the closing tag.

If you're trying to access the BODY element within a script in the HEAD
element, then that will fail as the BODY starting tag won't have been
encountered by the browser.
It is there in the document


The BODY element is /always/ present, even if you omit its tags (which
is permissible as they are optional). The HTML, HEAD, BODY, and TBODY
elements are all instances of elements which have optional starting and
closing tags, but in each case, they are /always/ present in the
document tree - they are implicit.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #17
On 14/07/2005 00:10, Robi wrote:

[snip]
I have noticed going to javascript websites
i.e. http://www.webreference.com/js/colum...pendchild.html
You will find that much of the material, both on the Web and in books,
is rubbish.

[snip]
I get "uncaught exceptions" which worry me,
In this particular instance, it's because the cloneNode method has a
required argument and the script omits it (the error message says as much).

You will find that IE doesn't support a lot of the W3C DOM (as
specified, at least), and that which is does support tends to be butchered.

For example, Microsoft made the argument to cloneNode optional. However,
because many people still only test with one browser (IE), they may take
advantage of this 'feature', unaware that it will render their code
unusable with other DOM-compliant browsers.
because it tells me that every single method/object needs to be
checked if it is supported or available in the agent used (mine or
someone elses).
Pretty much. There are very few assumptions you can make if you intend
to produce robust code, but it's not as bad as you make it sound.

[snip]
Is there any sense in scripting at all?


Of course, but no-one here said it would be simple to do well. Web
scripting is portrayed as easy, and to a certain degree it is. However,
most people that make such a claim aren't aware of the issues that
surround it. Aspects such as differing object models makes it a
discipline unlike most others.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #18
Michael Winter <m.******@blueyonder.co.uk> wrote:
As far as making object retrieval it's better to perform any tests once:

var getReferenceById = isGenericObject(document.getElementById)
? function(id) {

[...]

Is there any objection to saving document.getElementById and
reassigning this construct to the identifier (and using the original function
therein)?

Bye,
Martin
Jul 23 '05 #19
On 15/07/2005 11:57, Martin Bialasinski wrote:
Michael Winter <m.******@blueyonder.co.uk> wrote:
As far as making object retrieval it's better to perform any tests once:

var getReferenceById = isGenericObject(document.getElementById)
? function(id) {


[...]

Is there any objection to saving document.getElementById and
reassigning this construct to the identifier (and using the original
function therein)?


Yes. Some browsers (most notably Mozilla) requires the this operator to
refer to the document object. Calling the method directly would give the
operator a reference to the global object.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #20
Michael Winter <m.******@blueyonder.co.uk> wrote:
On 15/07/2005 11:57, Martin Bialasinski wrote:
Michael Winter <m.******@blueyonder.co.uk> wrote:
As far as making object retrieval it's better to perform any tests once:

var getReferenceById = isGenericObject(document.getElementById)
? function(id) {

[...]

Is there any objection to saving document.getElementById and
reassigning this construct to the identifier (and using the original
function therein)?


Yes. Some browsers (most notably Mozilla) requires the this operator
to refer to the document object. Calling the method directly would
give the operator a reference to the global object.


Just to clarify: You proposed function does not use "this".
So you mean the original getElementById internally uses "this" and assumes
that "this" refers to the document object.

And when used like

var gEBI = document.getElementById;
document.getElementById = function() { return gEBI(); }

"this" will refer to the global object in the original gEBI. Correct?

How about

document.gEBI = document.getElementById;
document.getElementById = function() { return this.gEBI(); }

or even explicitly
document.getElementById = function() { return document.gEBI(); }
Would not this make the function run in the correct context?

Bye,
Martin
Jul 23 '05 #21
On 15/07/2005 15:39, Martin Bialasinski wrote:
Michael Winter <m.******@blueyonder.co.uk> wrote:
[snip]
Some browsers (most notably Mozilla) requires the this operator to
refer to the document object. Calling the method directly would
give the operator a reference to the global object.


[snip]
So you mean the original getElementById internally uses "this" and
assumes that "this" refers to the document object.
From what I've observed, that's correct.
And when used like

var gEBI = document.getElementById;
document.getElementById = function() { return gEBI(); }

"this" will refer to the global object in the original gEBI. Correct?
Yes.
document.gEBI = document.getElementById;
document.getElementById = function() { return this.gEBI(); }

or even explicitly
document.getElementById = function() { return document.gEBI(); }

Would not this make the function run in the correct context?


It would, but there would be no advantage in doing so as the resulting
code would be slightly larger, but no quicker. You also rely on another
property existing on the document object. If that was overwritten, the
method would fail.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #22
Michael Winter <m.******@blueyonder.co.uk> wrote:
On 15/07/2005 15:39, Martin Bialasinski wrote:

document.gEBI = document.getElementById;
document.getElementById = function() { return this.gEBI(); }
Would not this make the function run in the correct context?


It would, but there would be no advantage in doing so as the resulting
code would be slightly larger, but no quicker. You also rely on
another property existing on the document object. If that was
overwritten, the method would fail.


Ok. I was thinking in the lines of adding Array.prototype.push for IE5
so one could always use document.getElementById no matter what.

if (!isGenericObject(document.getElementById)){

document.getElementById =
isObject(document.all)
? function(id) {
var result = document.all[id];

if(result) {
if(id == result.id) {
return result;
} else if(isGenericObject(result.item)) {
for(var i = 0,
n = result.length;
i < n;
++i)
{
if(id == result[i].id) {
return result[i];
}
}
}
}
return null;
}
: function() {return null;};
}

function isGenericObject(o) {
return isObject(o) || ('function' == typeof o);
}
function isObject(o) {
return 'object' == typeof o;
}

No need for a new getReferenceById interface, no additional property
in the document object. How about that?
As for the if(result) part, I turned the "if" and "else" part of the
inner condition around. As with

<form id="formid">
<input id="i1" name="i1">
<input id="i2" name="i1">
</form>

document.all["formid"] will return the form element, which behaves
like a collection with

result.id = "formid"
result.length = 2
result.item returning the input elements, so id == result[i].id will
never be true.
Bye,
Martin
Jul 23 '05 #23
On 17/07/2005 13:36, Martin Bialasinski wrote:

[snip]
I was thinking in the lines of adding Array.prototype.push for IE5
so one could always use document.getElementById no matter what.
[snip]
No need for a new getReferenceById interface, no additional property
in the document object. How about that?
There's no reason why not. However, other code that accompanies this
also wraps other DOM methods which don't exist solely on the document
object, so this method and others exist as methods of other objects.

[snip]
<form id="formid">
<input id="i1" name="i1">
<input id="i2" name="i1">
</form>

document.all["formid"] will return the form element, which behaves
like a collection with
[snip]
result.item returning the input elements


I didn't realise that IE had an item method on FORM elements. They
aren't collections (as such); that's what the elements collection is for.

An alternative to testing for the item method is to test for the tags
method. That should /only/ exist on collections.

Thank you,
Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #24


Yo can also help me if you got the solution to Robi's problem coz i also
have a simalar problem with ma code.

*** Sent via Developersdex http://www.developersdex.com ***
Aug 3 '05 #25

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by Andrea | last post: by
4 posts views Thread by the other john | last post: by
3 posts views Thread by GarryJones | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.