5

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 4

8
.text()
Sign up to request clarification or add additional context in comments.

Comments

2

Try this

var t = $('a').text();
alert(t);

http://jsfiddle.net/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();

2 Comments

why not just html() for jquery or innerHTML with javascript?
You could use either of those, too.
0

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

Comments

0

Try var LinkName = document.links.text; Or for IE you will need var LinkName = document.links.innerText

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.