Is it possible to grab a link by its href if it doesn't have a class or ID?

后端 未结 10 854
北恋
北恋 2021-01-07 08:56

I\'m using someone else\'s app and want to change the innerHTML in between any < a>< /a> tag that has a certain href. But these links don\'t have a class or ID associa

相关标签:
10条回答
  • 2021-01-07 09:19

    Try this

    $('a[href*="example.com"]');
    

    This will select the link that has example.com in the href attribute..

    0 讨论(0)
  • 2021-01-07 09:32

    you can do it with jquery: http://api.jquery.com/attribute-equals-selector/

    ex: linksToGoogle = $('a[href="http://google.com"]');

    0 讨论(0)
  • 2021-01-07 09:33

    Select all elements that have the example.com value in href attribute:

    Live Demo: http://jsfiddle.net/NTGQz/

    $('a[href*="example.com"]');
    

    You can also try this, just to be more specific and following the OP "ideal" answer:

    Live Demo: http://jsfiddle.net/ksZhZ/

    jQuery.fn.getElementsByHref = function(str){ return $('a[href*="' + str + '"]'); };
    
    $(document).ready(function(){        
       elems = $(this).getElementsByHref('example.com');
    });
    
    0 讨论(0)
  • 2021-01-07 09:34

    You can use a DOM3-attribute-selector (jQuery doc) to get all elements that contain a certain text in their href attribute. It would look like

    $('a[href*="example.com"]')
    

    However, that might not be what you actually want - not only urls to that domain might contain this string. You might do something like begins-with:

    $('a[href^="http://example.com"]')
    

    but to get an exact and possibly more complex match, you don't get around a custom filter:

    $('a[href]').filter( function() {
         return this.hostname == "example.com";
         // or check other properties of the anchor element
    })
    
    0 讨论(0)
提交回复
热议问题