Reputation: 1304
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
Reputation: 103388
Use textContext
instead.
if (inputs[i].textContent == "selected")
http://jsfiddle.net/k6cpvt5e/2/
Upvotes: 9
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
Reputation: 4358
Use .innerText
instead of .value
if (inputs[i].innerText == "selected")
Upvotes: 0
Reputation: 517
With jQuery:
$('a').each(function() {
if(this.text() == 'selected')
alert($(this).attr(' id'));
}
Upvotes: -1
Reputation: 15923
You can use innerText
as.
if (inputs[i].innerText == "selected")
Upvotes: 0
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);
}
}
}
Upvotes: 0
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