Example
<a href="example.html">Example Name</a>
I would like to get "Example Name"
I know I can do this with regex, but I'm looking for a simpler, faster approach. The closest I came was with Jquery using the .attr("href")
attribute. I tried putting .attr("title")
, but that doesn't work since I technically don't have a title there.
Example
<a href="example.html">Example Name</a>
I would like to get "Example Name"
I know I can do this with regex, but I'm looking for a simpler, faster approach. The closest I came was with Jquery using the .attr("href")
attribute. I tried putting .attr("title")
, but that doesn't work since I technically don't have a title there.
4 Answers
Reset to default 8.text()
Try this
var t = $('a').text();
alert(t);
http://jsfiddle/jasongennaro/gZsbW/
Of course, this targets the first link it encounters. Better if you can hook it to an ID
.
Example
<a href="example.html" id="linkName">Example Name</a>
Then
var t = $('#linkName').text();
You can use something like this, which works in regular Javascript...
This has the advantage that it will extract the text from things like:
<a href="#">This is a <i>link</i> with <b>markup</b></a>
var getText = function(el) {
var ret;
var txt = [],i=0;
if (!el) {
ret = "";
} else if (el.nodeType === 3) {
// No problem if it's a text node
ret = el.nodeValue;
} else {
// If there is more to it, then let's gather it all.
while(el.childNodes[i]) {
txt[txt.length] = self.getText(el.childNodes[i]);
i++;
}
// return the array as a string
ret = txt.join("");
}
return ret;
};
Try var LinkName = document.links.text;
Or for IE you will need var LinkName = document.links.innerText