Home > Net >  How to set class name of current anchor from js file?
How to set class name of current anchor from js file?

Time:08-17

I have written this simple js code to render two anchor elements to the html files.

//<a href="a1link,html">Link1</a>
let aElement1 = document.createElement("a");
aElement1.href = "a1link.html";
aElement1.innerHTML = "Link1";
document.body.appendChild(aElement1);

//<a href="a2link.html">Link2</a>
let aElement2 = document.createElement("a");
aElement2.href = "a2link.html";
aElement2.innerHTML = "Link2";
document.body.appendChild(aElement2);

The a1link.html and a2link.html are almost the same.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>A1 Link</title>

    <style>
        a {
            padding: 10px;
            border: 1px solid black;
            text-decoration: none;
            color: white;
            background-color: #222222;
            margin: 2px;
        }

        .active {
            background-color: red;
        }
    </style>
</head>
<body>
    <h1>A1 Link</h1>
    <script src="./scripts/index.js"></script>
</body>
</html>

I was trying to make the current anchor a class named active. I have tried with if else and the result was both of them got the active class.

I also tried with addEventListener method with click type parameter but, the result was working until the site refreshes and directs to the other link.

I am trying this in VS code with the file:/// protocol.

What do I need is some JS code to know on what site it is and make the current link of that site a class of active but the others have to remain without the class.

CodePudding user response:

Compare the current location with the URL in the link, and add the active class if they match.

//<a href="a1link,html">Link1</a>
let aElement1 = document.createElement("a");
aElement1.href = "a1link.html";
aElement1.innerHTML = "Link1";
document.body.appendChild(aElement1);
if (window.location.href.match(/a1link\.html/) {
  aElement1.classList.add('active');
}

//<a href="a2link.html">Link2</a>
let aElement2 = document.createElement("a");
aElement2.href = "a2link.html";
aElement2.innerHTML = "Link2";
document.body.appendChild(aElement2);
if (window.location.href.match(/a2link\.html/) {
  aElement2.classList.add('active');
}

  • Related