beny lim
beny lim

Reputation: 1304

Getting the text of a <a> tag

I am trying to get the text of all hyperlinks in my web page and check whether the text is "selected". If it is "selected", an alert showing the id will be prompted.

However, when I tried to use inputs[i].value to get the text of the , the result I gets was "undefined".

How can I go about doing it?

The following codes are for my hyperlinks:

<a href="www.google.com" id="1">selected</a>
<a href="www.facebook.com" id="2">select</a>
<a href="www.gmail.com" id="3">selected</a>
<button onclick="check()">Check!</button>

The following codes are for my javascript:

function check() {
    var inputs = document.getElementsByTagName('a');
    for(var i = 0; i < inputs.length; i += 1) {
        if (inputs[i].value == "selected")
        {
            alert(inputs[i].id);
        }
    }
}

Upvotes: 1

Views: 162

Answers (7)

Curtis
Curtis

Reputation: 103388

Use textContext instead.

if (inputs[i].textContent == "selected")

http://jsfiddle.net/k6cpvt5e/2/

Upvotes: 9

nanobar
nanobar

Reputation: 66405

Use innerText. It's not a value on the <a> but actually a text node inside it.

if (inputs[i].innerText === "selected")

Edit: Use innerHtml instead ;)

Upvotes: 2

SK.
SK.

Reputation: 4358

Use .innerText instead of .value

if (inputs[i].innerText == "selected")

Upvotes: 0

Gustav P Svensson
Gustav P Svensson

Reputation: 517

With jQuery:

$('a').each(function() {
    if(this.text() == 'selected')
        alert($(this).attr(' id'));
} 

Upvotes: -1

Tushar Gupta
Tushar Gupta

Reputation: 15923

You can use innerText as.

if (inputs[i].innerText == "selected")

Upvotes: 0

Malik Naik
Malik Naik

Reputation: 1502

Try this..

HTML

<a href="www.google.com" id="1">selected</a>
<a href="www.facebook.com" id="2">select</a>
<a href="www.gmail.com" id="3">selected</a>
<button onclick="check()">Check!</button>

Javascript

function check() {
                var inputs = document.getElementsByTagName('a');
                for(var i = 0; i < inputs.length; i++) {
                    if (inputs[i].innerHTML == "selected")
                    {
                        alert(inputs[i].id);
                    }
                }
            }

Check this fiddle

Upvotes: 0

Shrinivas Shukla
Shrinivas Shukla

Reputation: 4463

The correct way to access the text of <a> tag is .innerHTML NOT .value.

Check out this fiddle.

Here is the snippet.

function check() {
  var inputs = document.getElementsByTagName('a');
  for (var i = 0; i < inputs.length; i += 1) {
    if (inputs[i].innerHTML == "selected") {
      alert(inputs[i].id);
    }
  }
}
<a href="www.google.com" id="1">selected</a>

<a href="www.facebook.com" id="2">select</a>

<a href="www.gmail.com" id="3">selected</a>

<button onclick="check()">Check!</button>

Upvotes: 0

Related Questions