0

I am making a chrome extension and have this in my popup.html:

<nav id="secondary-nav">
    <ul>
        <li class="active">Prerender</li>
        <li>Prefetch</li>
        <li>Preconnect</li>
    </ul>
</nav>

What I want to do is to change the active link onclick in pure JS. How and where can I do that? Should I make it in the background.js?

Thank you.

Jordan Savage
  • 196
  • 2
  • 16
  • 2
    The background script runs in a separate hidden page. The popup is also a separate page [with its own devtools](https://stackoverflow.com/a/38920982). You need to create a popup.js file and load it in your popup.html by using a script tag. In that js file you can use the standard DOM methods such as document.querySelector and access className. Make sure to read about the [extension architecture](https://developer.chrome.com/extensions/overview) in the documentation and see how it's done in the [demo extensions](https://developer.chrome.com/extensions/samples) – wOxxOm Feb 06 '19 at 15:48

1 Answers1

1

According to the Google Developper documentation you can link any other JS file to your main html file.

<!DOCTYPE html>
<html>
...
  <body>

    <script src="popup.js"></script>
  </body>
</html>

And if you want to set the <li> active when you click on it, you should use something like this :

var menu = document.getElementById("menu");
var menu_items = menu.children;

for (var i = 0; i < menu_items.length; i++) {
  menu_items[i].onclick = function() {
    this.classList.add("active");
    
    // don't forget to reset the class of others
    for (var j = 0; j < menu_items.length; j++) {
      if (menu_items[j] != this) menu_items[j].classList.remove("active");
    }
  }
}
li.active {
  color: green;
}
<ul id="menu">
  <li class="active">link1</li>
  <li>link2</li>
  <li>link3</li>
  <li>link4</li>
</ul>
robinvrd
  • 1,760
  • 12
  • 28