I wonder if my script is all right. Please review my code:

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<style>
li {display:inline;}
a.active {background:red;}
</style>
<body>
<ul>
<li><a href="http://www.example.com/home">Home</a></li>
<li><a href="http://www.example.com/news">News</a></li>
<li><a href="http://www.example.com/contact">Contact</a></li>
</ul>
<script>
for (var i = 0; i < document.links.length; i++) {
}
}
</script>
</body>
</html>


# querySelectorAll

Here's another approach, if you don't mind older browsers. You can use querySelectorAll instead of document.links. That way, you end up with a smaller result set rather than all links, and save you CPU cycles for running the loop.

In this case, we get only those links that have the same href value as the current document url:

var links = document.querySelectorAll('a[href="'+document.URL+'"]');


However, note the browser compatibility and there are quirks across implementations.

## Not all links need active

Now if you think about it, not all links with the document.URL need to have active. Say you have active set the font to 2em. If you get all links that point to the same page, they'd be 2em in size, regardless of where they are in the page!

Most likely, you only need it for the primary navigation. Consider adding a class to further refine the result set.

<ul class="navigation">
<li><a href="http://www.example.com/home">Home</a></li>
<li><a href="http://www.example.com/news">News</a></li>
<li><a href="http://www.example.com/contact">Contact</a></li>
</ul>

// More specific CSS


# className

Now you have to note that setting className replaces it with the value, like this example. If the links you have happen to have existing classes (and styles that come with them), your script will unintentionally remove their styles due to the replaced className.

What you can do is get the existing className value, split them by spaces (multiple class names are separated by spaces), append your class name, join them back and then change the value, like I did here:

var element = document.getElementById('change');
var classNames = element.className.split(' ');
classNames.push('huge');
element.className = classNames.join(' ');


you can use these for <a> tag

a:link {color:#FF0000;}      /* unvisited link */
a:visited {color:#00FF00;}  /* visited link */
a:hover {color:#FF00FF;}  /* mouse over link */
a:active {color:#0000FF;}  /* selected link */


See this DEMO

• Thanks for the answer, but my question is mainly focused on the script tag. – Mori Jan 2 '14 at 11:49
• what do you want with script – CJ Ramki Jan 2 '14 at 12:51
• You have presented an alternative solution, but haven't reviewed the code. Please edit it to explain your reasoning (how your solution works and how it improves upon the original) so that everyone can learn from your thought process. – Toby Speight May 30 '18 at 14:29