开发者

Using Javascript to pull the url of a hyperlink with a class attribute

There wi开发者_C百科ll be only one link of a particular class on the page. I'm trying to write a javascript snippet that will find this:

<a href="http://www.stackoverflow.com" class="linkclass"> ... </a>

and return a string consisting of this:

http://www.stackoverflow.com

Thanks in advance everyone.


Try the following

var url = (function() {
  var all = document.getElementsByTagName("a");
  for (var i in all) {
    var cur = all[i];
    if (cur.getAttribute('class') === "linkclass") {
      return cur.getAttribute('href');
    }
  }
  return undefined;
})();

Note: If there is only ever one element of that class it would be much more efficient to give the element a unique id instead of a class. The code would then be much simpler

var url = document.getElementById('theUniqueId').getAttribute('href');


If there will be only one instance of a particular class then use an id and grab them with document.getElementById("linkID").href; If you can't do that then using the classes:

var links = document.getElementsByTagName("a");
var ref = "";
for(var i = 0; i < links.length; i++)
{
   if(links[i].className == "linkClass")
   {
      ref = links[i].href;
      break;
   }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜