user634850
user634850

Reputation: 515

Javascript passing one function to every anchor tags

how to get href attribute using javascript function to every anchor tags?

<a href="www.facebook.com" onclick="myurl(href)"> facebook</a><br>
<a href="www.youtube.com" onclick="myurl(href)">youtube </a><br>
<a href="www.google.com" onclick="myurl(href)">google </a><br>

<script> 


function myurl(href){

 alert(href);
}

</script>

Upvotes: 0

Views: 630

Answers (5)

Abdul Munim
Abdul Munim

Reputation: 19217

You have mentioned that you want to alert all the links. Why do you have to give onclick="myurl(this)" on your every anchor tag. If you have the same function for all your anchor tags. You might consider using this:

var elements = document.getElementsByTagName("a");
for(var i = 0; i < elements.length; i++) {
    elements[i].onclick = function () {
        alert(this.href);
    }
}

Upvotes: 0

vishakvkt
vishakvkt

Reputation: 864

Pass the object to javascript first

<a href="somesite.html" onclick="myurl(this)"> somebook </a>

Then do in your function.

function myurl(LinkObject) { alert(LinkObject.href); }

Upvotes: 0

Glenn Ferrie
Glenn Ferrie

Reputation: 10390

You should change your code accordingly:

<a href="www.facebook.com" onclick="myurl(this)"> facebook</a><br>
<a href="www.youtube.com" onclick="myurl(this)">youtube </a><br>
<a href="www.google.com" onclick="myurl(this)">google </a><br>
<script> 
    function myurl(el){
       alert(el.href);
    }
</script>

Upvotes: 0

Daniel Teichman
Daniel Teichman

Reputation: 610

<a href="www.facebook.com" onclick="myurl(this.href)"> facebook</a><br>
<a href="www.youtube.com" onclick="myurl(this.href)">youtube </a><br>
<a href="www.google.com" onclick="myurl(this.href)">google </a><br>

Upvotes: 1

SLaks
SLaks

Reputation: 887365

Just use this.href.

this refers to the DOM element that fired the event.

Upvotes: 3

Related Questions