How to extract a link from a href based on class?


I’m George beginner in programming world and I need some help in this project.

So I’m building a script that at the end of it I want to redirect (on the same tab not in a new one) to the link (in this page is in another page is and so on) inside of a href based on element class(e.g. class name aaa )

Every time the link is different but the class is always the same name : aaa (the class always contains only one link).

The methods I’ve tried seems to work only with clicks and copy the current pages url.

let url = location.href;
document.getElementsByClassName('aaa').innerHTML = url;

Only suitable extracting method I’ve found was Pythons BeautifulSoup Library.

Any thoughts on how am I going to extract the link ?

Thanks in advance.


Asked By: jioze



The following JavaScript code solves your problem:

var link = document.querySelector('.aaa').getAttribute('href');

Good luck!

Answered By: Fillyjonk

You can use querySelctor() (or querySelectorAll() if you have multiple link elements) to get references to the DOM elements that contain the link(s).

Then use getAttribute("href") to get the actual link value e.g. and finally redirect using window.location.replace("").

Here a small working example which should give you an idea how this could work.

const linkElement = document.querySelector(".aaa"); // only return the first element with that class
const link = linkElement.getAttribute("href")
console.log("Doing some other stuff...")
console.log("You will be redirected in 2 seconds...")
setTimeout(() => window.location.replace(link), 2000);

<a class="aaa" href="">
  <div>Something inside</div>

Answered By: Mushroomator
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.