Home > Back-end >  How to extract a link from a href based on class?
How to extract a link from a href based on class?

Time:09-21

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 link.com in another page is link1.com 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.

img

CodePudding user response:

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. https://www.wikipedia.org/ and finally redirect using window.location.replace("https://www.wikipedia.org/").

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  href="https://www.wikipedia.org/">
  <div>Something inside</div>
</a>

CodePudding user response:

The following JavaScript code solves your problem:

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

Good luck!

  • Related