View Full Version : My appendChild anchor fails to insert inside my new firstChild div.

Jules Manson
01-25-2006, 06:39 PM
This script is part of an elaborate script (buildNav) that creates navigation for all of my pages. I created styling and isolated this script into its bare essentials in order to troubleshoot it. I know how to use the insertBefore and appendChild functions as they work just fine for all other parts of my buildNav. My createAnchor function also works just fine for all other parts of my buildNav. The problem is that when I append a named anchor into my newly created first-child div it gets inserted outside of the div instead. This script produces no errors on MSIE 6.0, Firefox 1.5, and Opera 8.51 all running on Windows XP.

The goal of my script is to create the following HTML as a firstChild of the body tag.

<DIV class="newfirstchild"><A name="mytop" class="myanchor">this text should be lime and appear inside lime box</A></DIV>

The complete HTML is:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
window.onload = initPage;
function initPage(){buildNav();}
function buildNav(){
if (!document.getElementById('pc') || !document.createElement) return true;
var docBody = document.getElementById('pc');
function topAnchor(NODE){
var firstDiv = NODE.insertBefore(document.createElement('DIV'),NODE.firstChild);
firstDiv.className = 'newfirstchild';
createAnchor(NODE,'','this text should be lime and appear inside lime box','myanchor','mytop');
function createAnchor(NODE,HREF,TEXT,ACLASS,NAME){
var theAnchor = NODE.appendChild(document.createElement('A'));
if (HREF!=null && HREF!='') theAnchor.href = HREF;
if (TEXT!=null && TEXT!='') theAnchor.appendChild(document.createTextNode(TEXT));
if (ACLASS!=null && ACLASS!='') theAnchor.className = ACLASS;
if (NAME!=null && NAME!='') theAnchor.name = NAME;
DIV.newfirstchild{width:450px; height:20px; border:solid #0F0 1px;}/*this tests if new DIV inserts as first-child*/
DIV.newfirstchild A.myanchor{color:#0F0;}/*myanchor appears lime if it successfully inserts inside new DIV*/
A.myanchor{color:#F00;}/*myanchor appears red if it fails to insert inside new DIV*/
</HEAD><BODY ID="pc">
<DIV><H4>Header inside 1st child</H4><P>Blah blah blah.</P></DIV>
<DIV><H4>Header inside 2nd child</H4><P>Blah blah blah.</P></DIV>

I really do appreciate the help offered as this is evident in the countless hours that I spend with others in instant messaging helping them with Windows troubleshooting. However, please test your solution before providing one. If you cannot provide an adequate answer to my query please do not respond to this posting. Useless responses tend to make postings long, difficult to follow, and old. Thank you for your cooperation. :)

Jules Manson
01-25-2006, 08:40 PM
Nevermind everyone, this problem was solved by Fang at WebDeveloper.com (http://www.webdeveloper.com/forum/showthread.php?p=501879). It was a very minor logic error. :)