PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to extract a link from a href based on class?

 October 15, 2022     dom, html, javascript, python     No comments   

Issue

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


Solution

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



Answered By - Mushroomator
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing