473,837 Members | 1,558 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Help with using the dom to create a new link element and inserting it...

Hi,

I'm trying to understand how to work the dom, and all I'm trying to do
is insert a link right before another link in the html based on it's
href value. This isn't a real world example - I'm just trying to do
this in phases to understand what's going on. I'm getting an error
(Object doesn't support this property or method) in IE and I can't
figure out what I'm doing wrong. Can anyone tell me?

if (navigator.appN ame == "Microsoft Internet Explorer")
{
var browser="IE";
}
else
{
var browser="notIE" ;
}
var e = document.getEle mentById('conte ntWrapper');
if (e)
{
var a=e.getElements ByTagName('a');
for (var i=0;i<a.length; i++)
{
if (browser == "IE")
{
if (a[i].getAttribute(' href') != null &&
a[i].getAttribute(' href',2).indexO f("://") >= 0 &&
a[i].getAttribute(' href',2).indexO f("bcbsal.org ") == -1)
{
var iconLink = e.createElement ('a');
iconLink.href = a[i].href;
iconLink.title = 'This link takes you to another web site.';
iconLink.append Child(e.createT extNode('Test') );
a[i].title = 'This link takes you to another web site.';
a[i].parentNode.ins ertBefore(iconL ink,a[i]);
}
}
else....

Thanks!
Holli

May 12 '06 #1
14 2007
Well, I figured out that I have to change the e to document on this
line:

var iconLink = e.createElement ('a'); change to
var iconLink = document.create Element('a');

Now, IE just freezes. Now what? I'm guessing this will be an easy
answer for someone.

Thanks!
Holli

May 12 '06 #2
ASM
hg*****@bcbsal. org a écrit :
Hi,

I'm trying to understand how to work the dom, and all I'm trying to do
is insert a link right before another link in the html based on it's
href value. This isn't a real world example - I'm just trying to do
this in phases to understand what's going on. I'm getting an error
(Object doesn't support this property or method) in IE and I can't
figure out what I'm doing wrong. Can anyone tell me?

if (navigator.appN ame == "Microsoft Internet Explorer")
var IE = false; /*@cc_on IE = true; @*/
{
var browser="IE";
}
else
{
var browser="notIE" ;
}
var e = document.getEle mentById('conte ntWrapper');
if (e)
{
var a=e.getElements ByTagName('a');
for (var i=0;i<a.length; i++)
{
if (browser == "IE")
if(IE) {
if (a[i].getAttribute(' href') != null &&
a[i].getAttribute(' href',2).indexO f("://") >= 0 &&
a[i].getAttribute(' href',2).indexO f("bcbsal.org ") == -1)


var lk = a[i].href;
if( lk && lk.indexOf('://')>0 && lk.indexOf('bcb sal.org')<0)men t('a');
{
var iconLink = document.create Element('A');
iconLink.href = lk;
iconLink.title = 'This link takes you to another web site.';
iconLink.innerH TML = 'Test';
/*
or
iconLink.firstC hild.nodeValue = 'Test';
or
var tx = document.create TextNode('Test' );
inconLink.appen dChild(tx);
*/
a[i].title = 'This link takes you to another web site.';
a[i].parentNode.ins ertBefore(iconL ink,a[i]);
}
}
}
--
Stephane Moriaux et son [moins] vieux Mac
May 12 '06 #3
hg*****@bcbsal. org wrote:
Hi,

I'm trying to understand how to work the dom, and all I'm trying to do
is insert a link right before another link in the html based on it's
href value. This isn't a real world example - I'm just trying to do
this in phases to understand what's going on. I'm getting an error
(Object doesn't support this property or method) in IE and I can't
figure out what I'm doing wrong. Can anyone tell me?
Don't use tabs for indents in posted code, use 2 (preferred) or 4
spaces. Manually wrap code at about 70 characters to prevent
auto-wrapping, otherwise errors may be introduced there weren't in the
original code.


if (navigator.appN ame == "Microsoft Internet Explorer")
Ditch that straight away, browser sniffing has been out of vogue for
many years, feature detection is all the rage.

{
var browser="IE";
}
else
{
var browser="notIE" ;
}
var e = document.getEle mentById('conte ntWrapper');
It is much better to give your variables meaningful names, single
letters are OK for counters and such, your choice.

var wrapper;
if (document.getEl ementById){
wrapper = document.getEle mentById('conte ntWrapper');

if (e)
Good, you check that getElementById returned something. :-)

{
var a=e.getElements ByTagName('a');
'a' is now a collection of the 'A' elements that are decedents of
'contentWrapper '. A feature of such collections is that they are live -
as you add A elements to contentWrapper in your code below, they are
also added to the collection.

This has ramifications for your loop below - the length keeps getting
longer and because you insertBefore the current node, it will keep
inserting forever once the if condition is true.

for (var i=0;i<a.length; i++)
It is more efficient (though often not noticeably so) to get the length
of the collection once only. Getting the length every time in this case
will cause you go to into an endless loop because you keep inserting
nodes before the current one - better to loop from the end back to the
start using while, then the inserted nodes are beyond where you are
currently checking:

var i = a.length;
while (i--){

{
if (browser == "IE")
Ditch that.

{
if (a[i].getAttribute(' href') != null &&
a[i].getAttribute(' href',2).indexO f("://") >= 0 &&
a[i].getAttribute(' href',2).indexO f("bcbsal.org ") == -1)
It is easier to access properties directly, though it's not standard it
is better supported than get/setAttribute. It is also better to get a
reference to the element once and use that rather than lookup a[i]
multiple times:

var i = a.length;
while (i--){
tmp = a[i];

indexOf is pretty efficient, but rather than doing all those tests you
might consider using a regular expression and just the one test:

if ( /bcbsal\.org/.test(temp.href ) )
The above will return false if either the element doesn't have a value
for the href attribute or it doesn't match "bcbsal.org ". You might want
to also make the test case insensitive:

if ( /bcbsal\.org/i.test(temp.hre f) )

{
var iconLink = e.createElement ('a');
This is the line that is causing your error: 'e' is a reference to an
element, elements implement the HTML element interface which doesn't
have a createElement() method, that belongs to the HTML document
interface so you have to call it with 'document':

var iconLink = document.create Element('a');

Some links:

DOM 2 Core Document Interface:
<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#i-Document>

DOM 2 Core Element Interface:
<URL:http://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-745549614>

There are further interfaces defined in the DOM 2 HTML spec:
<URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html>

iconLink.href = a[i].href;
The problem here is that you insert an A element before a node, which
makes the node the i+1 node in the collection, so the next loop tests
the same node, matches the href, inserts another link, moves the node +1
again, etc. /ad infinitum/.

iconLink.title = 'This link takes you to another web site.';
iconLink.append Child(e.createT extNode('Test') );
Again, createTextNode is a method of document, not element:

iconLink.append Child(document. createTextNode( 'Test'));

a[i].title = 'This link takes you to another web site.';
a[i].parentNode.ins ertBefore(iconL ink,a[i]);
}
}
else....

Putting it all together:

<div id="contentWrap per"><br>
<a href="http://www.bcbsal.org" >bcbsal.org</a><br>
<a href="http://www.apple.com"> Apple a</a><br>
<a href="">Empty a</a><br>
</div>

<script type="text/javascript">

if (document.getEl ementById){
var wrapper = document.getEle mentById('conte ntWrapper');

if (wrapper){
var a = wrapper.getElem entsByTagName(' a');
var tmp;
var iconLink;
var i = a.length;

while (i--){
tmp = a[i];

if ( /bcbsal\.org/.test(tmp.href) ){
iconLink = document.create Element('a');
iconLink.href = tmp.href;
iconLink.title = 'This link takes you to another web site.';
iconLink.append Child(document. createTextNode( 'Test'));
tmp.title = 'This link takes you to another web site.';
tmp.parentNode. insertBefore(ic onLink,tmp);
}
}
}
}

</script>

--
Rob
Group FAQ: <URL:http://www.jibbering.c om/faq/>
May 12 '06 #4
RobG wrote:
[...]
for (var i=0;i<a.length; i++)


It is more efficient (though often not noticeably so) to get the length
of the collection once only. Getting the length every time in this case
will cause you go to into an endless loop because you keep inserting
nodes before the current one - better to loop from the end back to the
start using while, then the inserted nodes are beyond where you are
currently checking:

var i = a.length;
while (i--){


Another solution is to increment i a second time if the test is true,
but that may be bad for maintenance (then again, the reason for the
while loop may not be understood either...):

for (var i=0, len=a.length; i<len; i++){
if (...){
// insert element before current element
// increment i to account for inserted element
i++;
}
}
--
Rob
Group FAQ: <URL:http://www.jibbering.c om/faq/>
May 12 '06 #5
RobG said the following on 5/11/2006 9:54 PM:
RobG wrote:
[...]
for (var i=0;i<a.length; i++) It is more efficient (though often not noticeably so) to get the
length of the collection once only. Getting the length every time in
this case will cause you go to into an endless loop because you keep
inserting nodes before the current one - better to loop from the end
back to the start using while, then the inserted nodes are beyond
where you are currently checking:

var i = a.length;
while (i--){


Another solution is to increment i a second time if the test is true,
but that may be bad for maintenance (then again, the reason for the
while loop may not be understood either...):


Depending on what the intentions are. If you want to go through the
entire collection, then use the while. If you want to only do the first
one you find, then you can break; out of the for loop. That will keep
from going through a long collection to do only the first one.
for (var i=0, len=a.length; i<len; i++){

var len = a.length;
for (var i=0;i<len;i++)

Never cared for the len definition in the for loop :)
if (...){
// insert element before current element
// increment i to account for inserted element
i++;


break;
// :)

--
Randy
comp.lang.javas cript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
May 12 '06 #6
ASM
RobG a écrit :

This has ramifications for your loop below - the length keeps getting
longer and because you insertBefore the current node, it will keep
inserting forever once the if condition is true.

for (var i=0;i<a.length; i++)


Too much !
I thought a.length was seen once.

I now understand better :

for(var i=0, len=a.length; i<len; i++)
--
Stephane Moriaux et son [moins] vieux Mac
May 12 '06 #7
ASM wrote:
hg*****@bcbsal. org a écrit :

<snip>
if (navigator.appN ame == "Microsoft Internet Explorer")


var IE = false; /*@cc_on IE = true; @*/


But what is it about this script that would require an interest in
whether the browser is IE or not?

<snip>
a[i].getAttribute(' href',2).indexO f("bcbsal.org ") == -1)


var lk = a[i].href;
if( lk && lk.indexOf('://')>0 && lk.indexOf('bcb sal.org')<0)men t('a');

<snip> ^^^^^^^^^

You might want to correct that line as it radically alters the behaviour
of the following code.

Richard.


May 12 '06 #8
RobG wrote:
hg*****@bcbsal. org wrote:

<snip>
{
if (a[i].getAttribute(' href') != null &&
a[i].getAttribute(' href',2).indexO f("://") >= 0 &&
a[i].getAttribute(' href',2).indexO f("bcbsal.org ") == -1)


It is easier to access properties directly, though it's not
standard it is better supported than get/setAttribute. ...

<snip>

Not standard? Doesn't the W3C HTML DOM define a - href - property on the
HTMLAnchorEleme nt interface? Is there something that is more 'standard'
than the W3C DOM?

Richard.
May 12 '06 #9
Richard Cornford wrote:
RobG wrote:
hg*****@bcbsal. org wrote:

<snip>
{
if (a[i].getAttribute(' href') != null &&
a[i].getAttribute(' href',2).indexO f("://") >= 0 &&
a[i].getAttribute(' href',2).indexO f("bcbsal.org ") == -1)

It is easier to access properties directly, though it's not
standard it is better supported than get/setAttribute. ...

<snip>

Not standard? Doesn't the W3C HTML DOM define a - href - property on the
HTMLAnchorEleme nt interface? Is there something that is more 'standard'
than the W3C DOM?


The W3C Core specification has getAttribute and setAttribute, I figured
they are the 'standard' ways to get/set properties of DOM objects.
--
Rob
Group FAQ: <URL:http://www.jibbering.c om/faq/>
May 12 '06 #10

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

Similar topics

6
2751
by: Pete | last post by:
I am just getting to grips with XML and I was wondering if you could help me with something that no-one seems able or willing to help with.. I have an XSLT file which should be transforming a straight XML file http://www.discovertravelandtours.com/test/templates/test.xml?Location=Germany To another XML file http://www.discovertravelandtours.com/test/templates/test2.xml?Location=Germany
3
4713
by: Dante | last post by:
Tonight I started writing a script that places a "Copy All" link before every PRE tag. The link would copy the code in the pre tag. I can't get this script to work. Can anyone help me? Here is my script: function makeIt() { var where = document.getElementsByTagName("TABLE").childNodes.childNodes.childNodes.childNodes; var base = document.getElementsByTagName("PRE"); var link = document.createElement("SPAN"); var text =...
2
2045
by: dinks | last post by:
Hi, I'm new to C++ and have been assigned a task which i dont completely understand. Any help would be greately appreciated. Here is the problem: The class "linkedListType" use the "assert" facility. I am to get rid of them and replace them with exceptions. I need to create a "linkedListException" class that's declared and implemented in my "linkedListType" class. This class needs to inherit from the base "exception" class and return...
2
2148
by: . . | last post by:
Hi I need some help with java script . I have a ASPX page that is pulling a user message heading from the table on the page . The user message header has message body which suppose to dispay under the heading when a user click on the message header . Message body will come from database table .The different message header has different message body . I have got the message heading showing up on the web page . How do I show the message...
6
5007
by: James Radke | last post by:
Hello, I have a multithreaded windows NT service application (vb.net 2003) that I am working on (my first one), which reads a message queue and creates multiple threads to perform the processing for long running reports. When the processing is complete it uses crystal reports to load a template file, populate it, and then export it to a PDF. It works fine so far....
10
9787
by: free2cric | last post by:
Hi, I have a single link list which is sorted. structure of which is like typedef struct mylist { int num; struct mylist *next;
1
342
by: ankitvermamca | last post by:
I'm trying to dynamically add radio inputs to a form, but it's not working quite right. The code I have adds the radio buttons properly, but they are not selectable, and I can't seem to be able to retrieve the value. How do I fix it so they are selectable, and I can retrieve the value of the one the user selects? It only needs to work on IE5 or higher. Thanks in advance. Dex*
15
2916
by: Jaraba | last post by:
I am working in a project that I need to parse an arrayt an select records based upon the values parsed. I used the functions developed by Knut Stolze in his article 'Parsing Strings'. I am particulary having problems inserting records using a function. I am attaching the code for your review. Please, help. =================================--Function 1--====================================
0
5579
by: gunimpi | last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431 ******************************************************** VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help wanted ******************************************************** For this teeny job, please refer to: http://feeds.reddit.com/feed/8fu/?o=25
0
9683
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
10883
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
10578
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
10631
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
10276
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5670
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...
1
4477
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
4049
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
3126
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.