views:

131

answers:

3

I am trying to polish off a nav menu by having a script that fetches the current page name (via $_SERVER["PHP_SELF"]) and then in JavaScript finds the relevant name (i.e. from /contact.php finds just contact) and searches for an element with that id (my list items have ids that match their target). Now I want to swap the id of the element for "cur", which will confer upon it the relevant styling, making the tab of the current page display differently. But I am having problems, despite tryin replaceNode and replaceChild using the appropriate syntax. Here is the script in its longwinded form:

    function setCurPage() {

  var CurPage = "<?php echo $_SERVER["PHP_SELF"]; ?>"; // equates to "/contact.php"
  var CurRaw = CurPage.substr(1);
  var Cur = CurRaw.split(".")[0];
  var oldNode = document.getElementById(Cur);

var newNode = document.createElement("li");
newNode.id = "cur";
var innards = document.getElementById(Cur).children;
while(innards.length > 0) {
newNode.insertBefore(innards[0]);
}
oldNode.parentNode.replaceChild(newNode, oldNode);
}

I've tried various alerts and I know that the node creation lines are correct, but any alerts break after the replaceChild line. Anyone have any ideas?

A: 
oldNode.id = "cur";

ought to do all you need. If you want to be strict about it, you can use

oldNode.setAttribute("id", "cur");
NickFitz
+1  A: 

You want to use something like the following:

var newNode = oldNode.cloneNode(true);
newNode.id = "cur";
oldNode.parentNode.replaceChild(newNode, oldNode);
happytime harry
A: 

Okie dokies, I got it: instead of insertBefore, I now have appendChild and that works. I'll play with your suggestions anyway, in the interests of becoming better at using the DOM.