开发者

Get link name in javascript

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.


.text()


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


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜