获取<a> tag

时间:2015-07-16 11:44:38

标签: javascript html

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);
        }
    }
}

7 个答案:

答案 0 :(得分:9)

改为使用 $('ul.menu.fright').popover({ 'placement':'bottom', 'content':'Look at me!', delay: {show:500, hide:100} }).popover('show');

textContext

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

答案 1 :(得分:2)

使用innerText。它不是<a>上的值,而是其中的文本节点。

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

修改:改为使用innerHtml;)

答案 2 :(得分:0)

访问<a>代码文本的正确方法是.innerHTML .value

查看此fiddle

以下是摘录。

&#13;
&#13;
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);
    }
  }
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 3 :(得分:0)

试试这个..

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

答案 4 :(得分:0)

您可以使用innerText作为。

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

答案 5 :(得分:0)

使用.innerText代替.value

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

答案 6 :(得分:-1)

使用jQuery:

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