Javascript code working with Firefox but not with IE... please help!


J

John Ca

Hi all!

I'm a javascript newbie, and I wrote a function who's purpose is to
scan all paragraphs in a page, and then highlight certain keywords
which I provide in advance and turn them into hyperlinks! Simple
enough!

The problem is that the function works perfectly with Firefox (I am
using latest version 3.5.3), but with Internet Explorer it does not
work. I have tested it both with IE6 & IE7, and they both give me a
javascript error and the script doesn't do anything.

Since I am a total newbie when it comes to javascript I have
absolutely no idea what the problem could be, especially since the
script works as intended in Firefox! I would appreciate any help
anyone could provide...

I am calling the script function with an 'onload' event in the <body>
tag!

Here is my script:

function create_links() {

var KeywordsArray = new Array
("Keyword1","Keyword2","Keyword3","Keyword4")
var DocTextArray = document.getElementsByTagName("p")

for (y in DocTextArray) {

var DocText = document.getElementsByTagName("p")[y]
var DocTextContent = DocText.innerHTML
var DocTextNewContent

for (x in KeywordsArray)
{
var NewRegExp = new RegExp(KeywordsArray[x], "g");
DocTextContent = DocTextContent.replace(NewRegExp,"<a
href=\"http://www.mysite.com\">" + KeywordsArray[x] + "</a>")
}

DocText.innerHTML = DocTextContent
}
}



Thanks in advance to anyone willing to help out!!!

John
 
Ad

Advertisements

T

Thomas 'PointedEars' Lahn

John said:
[...]
The problem is that the function works perfectly with Firefox (I am
using latest version 3.5.3), but with Internet Explorer it does not
work. I have tested it both with IE6 & IE7, and they both give me a
javascript error and the script doesn't do anything.

Since I am a total newbie when it comes to javascript I have
absolutely no idea what the problem could be, [...]

The error message, which you have not posted, says what the problem is.
(Granted, IE error messages can be cryptic and misleading by comparison,
nevertheless you need to post them.) Please read the FAQ, especially
especially since the script works as intended in Firefox!

So what? Firefox is Gecko-based, IE is MSHTML-based. Gecko supports
Netscape/Mozilla.org JavaScript, IE/MSHTML supports Microsoft JScript.
[...]
I am calling the script function with an 'onload' event in the <body>
tag!

But you have not posted how you call it, which is rather important to know.
This is not a quiz show.
Thanks in advance to anyone willing to help out!!!

Thanks in advance for posting properly, including punctuation.


PointedEars
 
J

John Ca

Ok sorry, here is the requested information!

The error message I get is:

Line: 17
Char: 3
Error: 'undefined' is null or not an object
Code: 0

How I call the function is like this:

<body onload="create_links();">

Hope this clears things up!
 
R

RobG

Hi all!

I'm a javascript newbie, and I wrote a function who's purpose is to
scan all paragraphs in a page, and then highlight certain keywords
which I provide in advance and turn them into hyperlinks! Simple
enough!

I guess this is an exercise you have set yourself as a way of
learning.

The problem is that the function works perfectly with Firefox (I am
using latest version 3.5.3), but with Internet Explorer it does not
work. I have tested it both with IE6 & IE7, and they both give me a
javascript error and the script doesn't do anything.

As Thomas said, post the error message.
Since I am a total newbie when it comes to javascript I have
absolutely no idea what the problem could be, especially since the
script works as intended in Firefox! I would appreciate any help
anyone could provide...

I am calling the script function with an 'onload' event in the <body>
tag!

Here is my script:

function create_links() {

var KeywordsArray = new Array
("Keyword1","Keyword2","Keyword3","Keyword4")

It is more efficient to use an array literal:

var KeywordsArray = ["Keyword1", "Keyword2", "Keyword3",
"Keyword4"];

As a convention, variable names starting with capital letters are
reserved for constructors.

var DocTextArray = document.getElementsByTagName("p")

getElementsByTagName returns an HTML collection[1], which is *like* an
array in that its members can be accessed by index, but (in most
browsers) it lacks all the other special features of an array. So I
wouldn't call it an array, perhaps:

var pCollection = ...;

for (y in DocTextArray) {

It is not a good idea to use for..in to iterate over the members of an
array (even though what you have is just array-like) as it may well
return other properties of that object. I suspect that is your problem
with IE - it is enumerating properties that you don't expect.

You have a collection where the members can be accessed by index, so:

for (var i=0, len=pCollection.length; i<len; i++) {
var DocText = document.getElementsByTagName("p")[y]

You already have a reference to that collection, so don't get it again
on every iteration. Also, what it returns is a reference to a p
element, so name your variable to reflect that:

var p = pCollection;

It is considered a good idea to declare all variables at the start of
a function (except for those used in loops). Some prefer to declare
them where they are first used.
var DocTextContent = DocText.innerHTML

Using innerHTML is not always a good idea, though it should be OK here
provided your keywords don't match markup rather than content.
var DocTextNewContent

for (x in KeywordsArray)

Using for..in to iterate over the members of an array again, see
above. Use a normal for loop.

{
var NewRegExp = new RegExp(KeywordsArray[x], "g");

You probably only want to match whole words, so add that condition to
your regular expression:

var NewRegExp = new RegExp('\\b' + KeywordsArray[x] + '\\b','g');

DocTextContent = DocTextContent.replace(NewRegExp,"<a
href=\"http://www.mysite.com\">" + KeywordsArray[x] + "</a>")
}

DocText.innerHTML = DocTextContent

You can reduce the number of steps if you assign directly to the
innerHTML of the paragraph, e.g.

DocText.innerHTML = DocText.innerHTML.replace(...);



What you are trying to do has many foibles, it will only work well on
content that fits your criteria exactly. Search the archives, this
task has been attempted many times before. Here's a version of your
script that works in IE:

function create_links() {

var keywords = ['Keyword1','Keyword2','Keyword3','Keyword4'],
p,
pCollection = document.getElementsByTagName("p"),
re,
word;

for (var i=0, iLen=pCollection.length; i<iLen; i++) {
p = pCollection;

for (var j=0, jLen=keywords.length; j<jLen; j++) {
word = keywords[j];
re = new RegExp('\\b' + word + '\\b','g');
p.innerHTML = p.innerHTML.replace(re,
'<a href="http://www.mysite.com">' + word + '</a>');
}
}
}


1. <URL: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506 >
 
J

John Ca

Rob, thank you SO MUCH for taking all that time to help me and explain
everything step by step!!! The script you provided worked perfectly
with both IE & Firefox, and also your insights were very helpful to my
general understanding of Javascript!

Again thanks!!! I really appreciate it!!!

John
 
T

Thomas 'PointedEars' Lahn

John said:
Ok sorry, here is the requested information!

The error message I get is:

Line: 17
Char: 3
Error: 'undefined' is null or not an object
Code: 0

How I call the function is like this:

<body onload="create_links();">

Hope this clears things up!

Well, in itself it doesn't really clear things up, as you do not say where
line 17 is (and your unwise original line length makes it even harder to
guess). First think, then post. And read the FAQ.

However, now that RobG has pointed out the for-in iteration over a NodeList,
the error message indicates that something goes wrong with that. Indeed, my
test in IE 6 --

javascript:var ps = document.getElementsByTagName("p"); var a = []; for
(var p in ps) a.push(p); window.alert(a);

[in the address bar, at http://www.google.ch/]

-- shows that in the MSHTML DOM the returned NodeList instance has an
*enumerable* `length' property. Therefore,

var DocTextArray = document.getElementsByTagName("p")

for (y in DocTextArray) {

assigns

var DocText = document.getElementsByTagName("p")["length"];

at some point, after which the code would be equivalent to

var DocTextContent = (42).innerHTML
var DocTextNewContent

for (x in KeywordsArray)
{
var NewRegExp = new RegExp(KeywordsArray[x], "g");

(I use `42' as a dummy number here as you have not posted or linked to the
underlying markup, which you should have.)

Then the following line (which is probably line 17 or nearby) resolves to

DocTextContent = (undefined).replace(NewRegExp,"<a
href=\"http://www.mysite.com\">" + KeywordsArray[x] + "</a>")

And `undefined' *is* (null or) not an object, so it does not have a
replace() method to be called, which causes the aforementioned error
message.

Bottom line and solution: Do not use for-in iteration with host objects, use
classic for-loops. And use a debugger and make some cut-down tests before
complaining.


PointedEars
 
Ad

Advertisements

J

John Ca

Hey Thomas,

I think you have a major attitude problem man... but other than that
thanks for at least being *willing* to help, just leave all the
sarcasm to yourself next time! Cheers!

John
 
T

Thomas 'PointedEars' Lahn

John said:
I think you have a major attitude problem man... but other than that
thanks for at least being *willing* to help, just leave all the
sarcasm to yourself next time! Cheers!

If you think that my telling you exactly and in detaul where and how you
made mistakes included any kind of sarcasm, you are the one having a serious
attitude (and reading) problem for sure.

This is not a free help desk. Rest assured that I am not going to spend my
free time and help you next time. FOAD.


PointedEars
 
J

John Ca

If you think that my telling you exactly and in detaul where and how you
made mistakes included any kind of sarcasm, you are the one having a serious
attitude (and reading) problem for sure.

This is not a free help desk.  Rest assured that I am not going to spend my
free time and help you next time.  FOAD.

PointedEars
--
Use any version of Microsoft Frontpage to create your site.
(This won't prevent people from viewing your source, but no one
will want to steal it.)
  -- from <http://www.vortex-webdesign.com/help/hidesource.htm> (404-comp.)

It's free last time I checked... also I find it sad that you feel the
need to project your real life frustrations on an internet help board.
So much pent up aggression was obvious from your first message... and
your last message just proves my point.

No I will not "**** off and die", but you definitely need to get some
help/renew the meds prescription. Asshole.

Get out more... and have a nice life!
 
G

Gregor Kofler

John Ca meinte:
Hey Thomas,

I think you have a major attitude problem man... but other than that
thanks for at least being *willing* to help, just leave all the
sarcasm to yourself next time! Cheers!

I read Thomas' psoting twice. What sarcasm are you talking about? (By
Thomas' standards that was in fact a pretty tame response.) Instead you
got a detailled explanation, why you can't iterate over the nodelist
with for .. in. What's your problem with that?

Gregor
 
D

DonO

John Ca meinte:



I read Thomas' psoting twice. What sarcasm are you talking about? (By
Thomas' standards that was in fact a pretty tame response.) Instead you
got a detailled explanation, why you can't iterate over the nodelist
with for .. in. What's your problem with that?

Gregor

--http://www.gregorkofler.com

I think perhaps he's referencing such snarky remarks as...

"Thanks in advance for posting properly, including punctuation."

Making fun of his TIA for the help.

In a later post however, he says, "If you think that my telling you
exactly and in *detaul* where and how you
made mistakes" so it's good to see we're all prone to errors I
suppose.

FWIW I'd rather people help or not help. I deal with enough
personalities in my regular job.

$0.02
 
Ad

Advertisements

G

GTalbot

John Ca meinte:



I read Thomas' psoting twice. What sarcasm are you talking about?

"Instruction manual" directives just to post can certainly frustrate
people. The tone with which PointedEars reply can make anyone feel
inferior, especially the way he replies. Over-excessively nitpicking
too. It seems it never occurred to people like PointedEars that he is
obnoxious, authoritative, absolutely abrasive. PointedEars has weak
social skills.

"First think, then post. And read the FAQ. ": is that the kind of
useful help one should (or would) expect when posting in c.l.j.?

That famous c.l.j. FAQ is pretty long (89 Kilo-bytes; over 2000
lines); it is sometimes vague and it is referring to furthermore
reading ... to just post something in c.l.j.

Posting Questions and Replies to comp.lang.javascript
http://jibbering.com/faq/faq_notes/clj_posts.html
is 61 Kilo-bytes of more reading ... just to post at c.l.j.!

Realistically speaking, a perfectly willing, obedient, compliant
reader would have to read 150Kb before posting anything. And the first
thing to do for him/her before posting would be to "Read recent
relevant posts in c.l.js." How many? How recent? a week? a month?? How
does one establish/distinguish what is and what is not a relevant post
before making his first post in c.l.j.?


(By
Thomas' standards that was in fact a pretty tame response.) Instead you
got a detailled explanation,

The tone matters. The precise choice of words matters too. PointedEars
will always be perceived by a large majority of people to have an
attitude problem.

"This is not a quiz show.",
"Thanks in advance for posting properly, including punctuation. "
"Please read the FAQ, especially
<http://jibbering.com/faq/#posting>, and act accordingly. "
etc.: very typical PointedEars domesticating responses. Absolutely
unneeded, unnecessarly abrasive.

"FOAD": if that's not verbal abuse - and totally unneeded - , then
what is it?

Gérard
 
O

Osmo Saarikumpu

GTalbot kirjoitti:
"Instruction manual" directives just to post can certainly frustrate
people.

But certainly only people that really do not want the help that they need?
The tone with which PointedEars reply can make anyone feel
inferior, especially the way he replies.

Which tone? There is no tone in USENET or email messages. Your "tone" is
in the eye of the beholder. Rule of thumb: always read messages without
tone.
Over-excessively nitpicking
too. It seems it never occurred to people like PointedEars that he is
obnoxious, authoritative, absolutely abrasive. PointedEars has weak
social skills.

You are missing the point and everything with it. See what's happening?

1) You are off topic.
2) You are taking me with you.

And I'd willing to bet $10 that you are in no position to judge his
personality.
"First think, then post. And read the FAQ. ": is that the kind of
useful help one should (or would) expect when posting in c.l.j.?

I guess that is, if not what one would expect, what one needs. And that
exactly. I for one should print that and stick it between me and the
send button :)
Realistically speaking, a perfectly willing, obedient, compliant
reader would have to read 150Kb before posting anything. And the first
thing to do for him/her before posting would be to "Read recent
relevant posts in c.l.js." How many? How recent? a week? a month?? How
does one establish/distinguish what is and what is not a relevant post
before making his first post in c.l.j.?

It's not like that. One should read the FAQ "before posting" section and
search the FAQ for his/hers issue. If not a FAQ, then search cljs.
Posting comes after that. Preferably asking smart questions. That is,
if one would prefer to skip kindergarten.
The tone matters. The precise choice of words matters too. PointedEars
will always be perceived by a large majority of people to have an
attitude problem.

Do you have statistics on that? And if it were true, that would tells us
what? Majority rules?
"This is not a quiz show.",
"Thanks in advance for posting properly, including punctuation. "
"Please read the FAQ, especially
<http://jibbering.com/faq/#posting>, and act accordingly. "
etc.: very typical PointedEars domesticating responses. Absolutely
unneeded, unnecessarly abrasive.

I beg to disagree. Most certainly needed. Indispensable and to the
point. The more I think about it, the more life or dead issue it
USENETwisely becomes.
"FOAD": if that's not verbal abuse - and totally unneeded - , then
what is it?

I've never seen FOAD by PE as 1st advice. Have you? It's reserved only
for the obtuse && unteachable.

Now I'll have to brace myself, because I'm pretty sure that PE is going
to (justly) rebuke me for not being on topic.
 
Ad

Advertisements

T

Thomas 'PointedEars' Lahn

Osmo said:
GTalbot kirjoitti:

I've never seen FOAD by PE as 1st advice. Have you? It's reserved only
for the obtuse && unteachable.

ACK. For reasons now quite inexplicable to me, I had actually spent half
the night explaining in detail to this luser where he f***ed up. And then I
got this incredibly stupid response just before I went to bed. It just
needed to be said for having a good night's sleep. (Not very logical of me,
I know ...)
Now I'll have to brace myself, because I'm pretty sure that PE is going
to (justly) rebuke me for not being on topic.

As you wish:

+-------------------+ .:\:\:/:/:.
| PLEASE DO NOT | :.:\:\:/:/:.:
| FEED THE TROLLS | :=.' - - '.=:
| | '=(\ 9 9 /)='
| Thank you, | ( (_) )
| Management | /`-vvv-'\
+-------------------+ / \
| | @@@ / /|,,,,,|\ \
| | @@@ /_// /^\ \\_\
@[email protected]@[email protected] | | |/ WW( ( ) )WW
\||||/ | | \| __\,,\ /,,/__
\||/ | | | (______Y______)
/\/\/\/\/\/\/\/\//\/\\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\
==================================================================

:)


Regards,

(F'up2) PointedEars
 
G

GTalbot

GTalbot kirjoitti:


But certainly only people that really do not want the help that they need?

The OP wanted help and he provided quite a bit of useful details (not
all, maybe not enough). With PointedEars, it quickly aggravated into
verbal abuse.
I do not think the OP had a bad initial post. It needed a few
questions to be answered but that's it. I've seen much worse initial
post from newbies.
The OP stated twice that he was a newbie.
Which tone?

You certainly understand what I mean by tone. Pedantic tone. Abrasive
remarks. Talking down remarks. *That* tone.
There is no tone in USENET or email messages. Your "tone" is
in the eye of the beholder. Rule of thumb: always read messages without
tone.

I have read the messages without any inferred tone. Many replies from
PointedEars demonstrate lack of diplomacy and poor social skills. And
a willingness to engage (fight) people over formalisms of all sorts.
You are missing the point and everything with it.

Over-excessively pointing people to the FAQ should be addressed one
day. People shouldn't have to read 61 Kb just to post a question in
c.l.js.
This thread started with a question, need for assistance: it had
already enough useful details (sufficient chunk of relevant code;
browser and browser versions mentioned) to at least continue. It ended
up into verbal abuse.
See what's happening?

1) You are off topic.
2) You are taking me with you.


You chose to reply. I am not responsible for your decisions, your
typing, your freedom. Same thing with PointedEars: he chooses his
words, he chooses to engage not perfect-from-the-start posting in
here. He is abrasive and pedantic.
And I'd willing to bet $10 that you are in no position to judge his
personality.


I don't need a full program course in psychology to know that he is
abrasive, nitpicking, unneedlessly pedantic. The way he replies, the
words he chooses, the manners of addressing people reveal his social
skills.
I guess that is, if not what one would expect, what one needs. And that
exactly. I for one should print that and stick it between me and the
send button :)


It's not like that.

It is like that. FAQ section 1.3 has 7 links for more reading!
And anyone posting for the first time a question in c.l.js will most
likely not know that there is a FAQ to read before posting.
Posting comes after that. Preferably asking smart questions. That is,
if one would prefer to skip kindergarten.

Right here, you "sound" like PointedEars.

I've never seen FOAD by PE as 1st advice. Have you? It's reserved only
for the obtuse && unteachable.

I don't think the OP was obtuse, unteachable, narrow-minded or
unwilling to compromise over some posting rules or some other points
of formalism.
There is no need whatsoever for verbal abuse in c.l.js. If you can't
stand a post, then don't reply. If that is not in the FAQ (and related
webpages), then it should be.

Gérard
 
J

JR

The OP wanted help and he provided quite a bit of useful details (not
all, maybe not enough). With PointedEars, it quickly aggravated into
verbal abuse.
I do not think the OP had a bad initial post. It needed a few
questions to be answered but that's it. I've seen much worse initial
post from newbies.
The OP stated twice that he was a newbie.



You certainly understand what I mean by tone. Pedantic tone. Abrasive
remarks. Talking down remarks. *That* tone.


I have read the messages without any inferred tone. Many replies from
PointedEars demonstrate lack of diplomacy and poor social skills. And
a willingness to engage (fight) people over formalisms of all sorts.



Over-excessively pointing people to the FAQ should be addressed one
day. People shouldn't have to read 61 Kb just to post a question in
c.l.js.
This thread started with a question, need for assistance: it had
already enough useful details (sufficient chunk of relevant code;
browser and browser versions mentioned) to at least continue. It ended
up into verbal abuse.



You chose to reply. I am not responsible for your decisions, your
typing, your freedom. Same thing with PointedEars: he chooses his
words, he chooses to engage not perfect-from-the-start posting in
here. He is abrasive and pedantic.


I don't need a full program course in psychology to know that he is
abrasive, nitpicking, unneedlessly pedantic. The way he replies, the
words he chooses, the manners of addressing people reveal his social
skills.




It is like that. FAQ section 1.3 has 7 links for more reading!
And anyone posting for the first time a question in c.l.js will most
likely not know that there is a FAQ to read before posting.


Right here, you "sound" like PointedEars.



I don't think the OP was obtuse, unteachable, narrow-minded or
unwilling to compromise over some posting rules or some other points
of formalism.
There is no need whatsoever for verbal abuse in c.l.js. If you can't
stand a post, then don't reply. If that is not in the FAQ (and related
webpages), then it should be.


There has been a 'poll' about TPE sometime ago:
http://groups.google.la/group/comp.lang.javascript/browse_thread/thread/c2f869a0a0e48bf6

Unfortunately, to get on with TPE is like 'to carry a heavy burden up
the hill'. The alternative is to killfile him - for those who dislike
his antics.
 
Ad

Advertisements

G

Garrett Smith

Thomas said:
ACK. For reasons now quite inexplicable to me, I had actually spent half
the night explaining in detail to this luser where he f***ed up. And then I
got this incredibly stupid response just before I went to bed. It just
needed to be said for having a good night's sleep. (Not very logical of me,
I know ...)

OK. I'll Think twice about sending mails at night.

I'll try to refrain from posting things that make me look bad and take
away from all the hard work I put into trying to help someone.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top