Search code examples
jqueryhref

jQuery - find anchor by href value using a variable


I have a problem with selecting by href value assigned to a variable.

This code works as expected: $('a[href="/sites/example/page.aspx"]')

However, if I assign the above url to a variable, it doesn't find the href. e.g.

var myurl = "/sites/example/page.aspx" $('a[href=myurl]')

I tried entering the variable with or without quotes and a few different ideas, but can't get to it. What am I doing wrong?

Thanks!


Solution

  • You should use concatenation sign + to concatenate the variable to the selector else the selector will be something like :

    a[href=myurl]
    

    Instead of :

    a[href="/sites/example/page.aspx"]
    

    var myurl = "/sites/example/page.aspx";
    
    console.log($('a[href="' + myurl + '"]').text());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    
    <a href="/sites/example/page.aspx">Test</a>