Jump to content

get value and text from an anchor tag?


galvin

Recommended Posts

If I have this anchor in my HTML...

 

<a class="team" name="pick1" onclick="win(this)" value="2">Team 2</a>

 

...1. how do I get the VALUE (in this case "2") using Javascript?

 

2.  how do I get the text "Team 2"?

 

I know getElementById but my anchor tags don't have IDs and I don't want to give them any because I know there is another way.  Can anyone help?

 

 

 

Link to comment
https://forums.phpfreaks.com/topic/197051-get-value-and-text-from-an-anchor-tag/
Share on other sites

There are many ways.. From your code, are you going to get those value in your 'win' function?

If that is the case, it's easy:

function win(anchor) {
    var value = anchor.getAttribute('value');  // This give you '2'
    var html = anchor.innerHTML;  // This give you 'Team 2'
}

But if you want to access from somewhere else without using ID, you must get the reference using it's name:

var anchors = document.getElementsByName('pick1');
var myAnchor = anchors[0];
var value = myAnchor .getAttribute('value');  // This give you '2'
var html = myAnchor .innerHTML;  // This give you 'Team 2'

 

Hope this help.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.