最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

jquery - Get link name in javascript - Stack Overflow

programmeradmin3浏览0评论

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.

Share Improve this question asked Jul 25, 2011 at 1:55 stanstan 4,9956 gold badges51 silver badges76 bronze badges
Add a ment  | 

4 Answers 4

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

发布评论

评论列表(0)

  1. 暂无评论