I want to style a list using JavaScript to add a class to the active firstlevel list-item. So if you click ‘Flyer’, <li><a href="#">Downloads »</a> becomes <li class="active"><a href="#">Downloads »</a>.
HTML
<ul id="navmenu">
<li><a href="#">Downloads »</a>
<ul>
<li><a href="downloads_flyer.php">Flyer</a></li>
<li><a href="downloads_jahresberichte.php">Jahresberichte</a></li>
<li><a href="downloads_banner.php">Banner</a></li>
</ul>
</li>
<li><a href="presse.php">Pressecenter</a></li>
<li><a href="kontakt.php">Kontakt</a></li>
</ul>
JAVASCRIPT (updated)
var i = 0;
var url = "<?php echo end(explode("/", $_SERVER["SCRIPT_NAME"])); ?>";
var liste = document.getElementById("navmenu").getElementsByTagName("li");
while(i < liste.length) {
var topList = liste[i];
var topLink = liste[i].getElementsByTagName("a")[0];
if (topLink.href.substr((topLink.href.length - 1), 1) != "#" // To avoid matching the 'Downloads' link.
&& topLink.href.indexOf(url) > 0)
{
topList.className = "active";
}
i++;
}
As you can see it adds ‘active’ to the LI containing the link but it should be added to the toplevel LI.
How can I get the script running correctly – what is my mistake?
Final Solution
var i = 0;
var url = "<?php echo end(explode("/", $_SERVER["SCRIPT_NAME"])); ?>";
var liste = document.getElementById("navmenu").getElementsByTagName("li");
while(i < liste.length) {
var topLink = liste[i].getElementsByTagName("a")[0];
if (topLink.href.substr((topLink.href.length - 1), 1) != "#" // To avoid matching the 'Downloads' link.
&& topLink.href.indexOf(url) > 0)
{
if(topLink.parentNode.parentNode.parentNode.tagName == "LI") {
topLink.parentNode.parentNode.parentNode.className = "active";
} else {
topLink.parentNode.className = "active";
}
}
i++;
}
Thanks for your help guys!
You have to increment you var
i. Your while enters on an infinite loop! Intead of usedocument.URL, try using$_SERVER['SCRIPT_NAME']: