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

javascript - accessing href attribute with classname - Stack Overflow

programmeradmin5浏览0评论

I want to access the href attribute with jquery using the class name. How can I do that below is the code.

<a href="www.google" class="class-name">Hyper Link</a>

I only want to access it with the class-name since I have many links and want to use the classname to access the href link.

Thanks

I want to access the href attribute with jquery using the class name. How can I do that below is the code.

<a href="www.google." class="class-name">Hyper Link</a>

I only want to access it with the class-name since I have many links and want to use the classname to access the href link.

Thanks

Share Improve this question asked Jun 15, 2011 at 17:36 JayJay 3131 gold badge5 silver badges11 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4
$('a.class-name').each(function(){
     this.href //do something with href
})

Presuming (1) that you are using jQuery 1.6 and (2) that your link is the only one that has that class:

var linkHref = $('a.class-name').prop('href');

If you are using jQuery 1.5 or older, you'll have to use attr rather than prop. If you have more than one element with the class, you'll have to find some other way of identifying which element you want.

Depends what you want - but the href of your link should probably be made into an absolute rather than relative link...

    $('a.class-name').each(function(){
        alert( this.href ) // alerts http://currentdomain./www.google.
        alert( $(this).attr('href') ) // alerts www.google.
    })

To make the element look up faster I'd suggest dropping the tag prefix since you mentioned you have a lot of links.

$('.class-name').prop('href');
发布评论

评论列表(0)

  1. 暂无评论