Target the css class with some JS

Rate this post

Hello I currently have this inline JS on my wordpress navigation menu

<a href="" onclick="window.location = ''+window.location.href; return false;">login</a>

I was told it is better to use a regular menu item then just give it a class then target the class with some JS. I tried searching for examples but can’t find that works for me. Could someone share a sample code to point me in the right direction?




I think this is what you are told.


var link = document.querySelector(".js-link");
link.addEventListener("click", (e) => {
  //do whatever you want hear
  console.log("redirect to another page");
<a href="" class="js-link">Google</a>

The way you do will make your code messy, hard to read and maintain. So we should separate html, css and js code. And to make your javascript and style not affect each other when you change your code, you should naming the class which you want to use javascript different with class you want to style.

For example I using class “js-link” just for javascript, not to style it. If I want to style the link I will add another class for it.

Leave a Reply

Your email address will not be published.

Back to top button