Highlighting links with JavaScript
Tags: javascript
Published: 2019-10-05 20:53:11

---
title: Highlighting links with JavaScript
published: true
description: 
tags: javascript
---
As a web developer or just a curious mind navigating the web you might find yourself in a situation where you need to highlight link(s) on a specific webpage or HTML document but the only thing you are armed with is just a word from the url.

Lets take an hypothetical situation that you are on __WebsiteA__ and you are certain that __WebsiteA__ contains link(s) to another specific website you will like to navigate to, lets call it __WebsiteB__. Hunting down the specific link(s) might be time consuming if __WebsiteA__ contains lots of links. Using JavaScript we can highlight these links __even if the only thing we remember from the url is just a single word__.

When you are on __WebsiteA__, open your Developer Tools (Ctrl + Shift + I  in Firefox and Chrome), I am currently viewing the MDN website with FireFox.

![Mozilla Developer Network with Developer Tools opened](https://thepracticaldev.s3.amazonaws.com/i/jkorm5vykn401ets4mhh.PNG)

If there are any output in the console, click on the trash icon located at the top left corner to get rid of them. Lets make a list of what we want to do in order to highlight any link:

1. We get all the links on the page
2. We loop through the result
	* if any link contain our keyword
	* we highlight it
		1. changing the font weight
		2. change the background color
		3. apply a color to the link to make it readable on the backgroubnd color

In computer science, this is known as an algorithm which can be defined as:

> In mathematics and computer science, an algorithm is a sequence of instructions, typically to solve a class of problems or perform a computation. - [Wikipedia](https://en.wikipedia.org/wiki/Algorithm) 

Lets turn our algorithm to code.

In order to get all the links on a page, we can use JavaScript `documents.getElementsByTagName()` method and the HTML tag we will pass to it will be the anchor tag `a` which is used to create links in HTML. The resulting anchor tags is an `HTMLCollection`

![An example of HTMLCollection](https://thepracticaldev.s3.amazonaws.com/i/s1ahzged1boe016pzeoa.PNG)

Next we loop through the result

```javascript
// loop through it, since its an  HTMLCollection
for (let i = 0; i < link.length; i++) {
}
```

HTML links have the `href` attribute which contains the url of the resource we a linking to, we get this value in JavaScript by selecting an element from the `HTMLCollection` with the  `href` method as depicted in the image below:

![HTML link with href attribute](https://thepracticaldev.s3.amazonaws.com/i/49rurfddu86ppt5t2y07.PNG)

and to check if any of its element contain our keyword, we use the `.includes()` method

![JavaScript includes method](https://thepracticaldev.s3.amazonaws.com/i/xji11d81w5dde8i4fl30.PNG)

which returns true if the keyword is found in the  string

![JavaScript includes method returns true](https://thepracticaldev.s3.amazonaws.com/i/kzv9gcrbb9nu0hewe2n0.PNG)

and false otherwise

![JavaScript includes method returns false](https://thepracticaldev.s3.amazonaws.com/i/f70rimqb8ybcqhdbcb2p.PNG)

If it returns true, that means our keyword was found and we can perform the necessary action on it, in this case we highlight the link by changing its `font-weight` and `background-color` just to make it stand out

```javascript
// loop through it, since its an  HTMLCollection
for (let i = 0; i < link.length; i++) {

  // if link includes our keyword, in this case the word
  // 'hacks'
  if (links[i].href.includes('hacks')) {

     // change the link background color
     links[i].style.backgroundColor = "#1560bd";

     // change the text color
     links[i].style.color = "#ffffff";

     // change the font weight
     links[i].style.fontWeight = "bold";
   }

}
```

And code from step1 and step 2 combined:

```javascript
// get all anchor tags
let link = document.getElementsByTagName('a');

// loop through it, since its an  HTMLCollection
for (let i = 0; i < link.length; i++) {

  // if link includes our keyword, in this case the word
  // 'hacks'
  if (link[i].href.includes('hacks')) {

     // change the link background color
     link[i].style.backgroundColor = "#1560bd";

     // change the text color
     link[i].style.color = "#ffffff";

     // change the font weight
     link[i].style.fontWeight = "bold";

   }

}
```

The code be used on your web page of choice. Below, i have  highlighted some link(s) on the MDN home page.

![Highlighted links on the Mozilla Developer Network](https://thepracticaldev.s3.amazonaws.com/i/c641n28i5mavqmermkvn.png)

If you'd rather work with a local html file, the procedure is the same but here are some code snippet you can work with. First the HTML, copy and paste in your code editor and save as __colorlinks.html__

```html
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>Highlighting Links with JavaScript</title>
	<link rel="stylesheet" href="colorlinks.css">
</head>
</head>
<body>
  <ul>
    <li><a href="https://google.com">Google</a></li>
    <li><a href="https://toptal.com">Toptal</a></li>
    <li><a href="https://twitter.com">Twitter</a></li>
    <li><a href="https://toptal.com">Toptal</a></li>
    <li><a href="https://mobile.twitter.com">Mobile Twitter</a></li>
  </ul>
</body>
</html>
```
The CSS (for cosmetics), copy and paste in your code editor and save as __colorlinks.css__

```css
/* ========== Cosmetics ============== */
body {
  background-color: #f9f9fa;
}

ul {
  border: 2px solid #cccccc;
  padding: 0;
  width: 100%;
}

@media screen and (min-width: 48em) {
  ul {
    width: 60%;
    margin: 0 auto;
  }
}

li {
  list-style: none;
  border-bottom: 1px solid #cccccc;
  margin: 0;
}

a {
  text-decoration: none;
  color: #1560bd;
  font-size: 120%;
  display: block;
  padding: 8px 16px;
}

.highlighted {
  font-weight: bold;
  background-color: #1560bd;
  color: #ffffff;
}
```
and the JavaScript, create opening and closing `script` tag just above the closing `</body>` tag, copy the following code and paste between the tags:

```javascript
// get all anchor tags
let link = document.getElementsByTagName('a');

// loop through it, since its an  HTMLCollection
for (let i = 0; i < link.length; i++) {

  // if link includes our keyword, in this case the word
  // 'tal'
  if (link[i].href.includes('tal')) {

     // add the highlighted class
     links[i].classList.add('highlighted');

   }

}
```

Taking a closer look at the JavaScript code, you'll realize we are not applying inline styles, instead we've opt to add an `.highlighted` CSS class to the link to just keep things simple (kind of).

Save all files (the html and css), and load the file in your browser, you should get an output similar to the image below:

![Highlighted Links](https://thepracticaldev.s3.amazonaws.com/i/qrxmnrhd3t8ip032q6ii.png)

Have Fun!.