Burhan Mughal
Burhan Mughal

Reputation: 818

Extracting Anchor tag with text separately

I am in JavaScript, I want to extract link from my anchor tag and text of the anchor separately. i.e. I have following anchor tag.

<a href="http://www.defconpaintball.com/hiring">Learn More</a>

I want to get the "href" in separate variable and the text "Learn More" in separate variable. How I can do this?

Upvotes: 0

Views: 1556

Answers (2)

loxxy
loxxy

Reputation: 13151

Give it an id

<a id="myLink" href="http://www.defconpaintball.com/hiring">Learn More</a>

Here is a fiddle, you can play with.

var anchor = document.getElementById("myLink");

alert(anchor.getAttribute("href")); // Extract link

alert(anchor.innerHTML); // Extract Text

EDIT:

Don't know what is preventing you from parsing the whole content.

Something like this should be enough:

var anchors = document.getElementsByTagName("a");

for(var i in anchors) 
    if(anchors[i].innerHTML=="Learn More") 
        alert(anchors[i].getAttribute("href"));

Here is another fiddle.

Upvotes: 1

EnterJQ
EnterJQ

Reputation: 1014

try this

 anchor.getAttribute("href")

OR

<a  href="relativeURL" >
var link = element.a.getAttribute('href')

EDIT : I have updated code , try with that

Upvotes: 2

Related Questions