Alen
Alen

Reputation: 1291

How to find an anchor tag with respect to href

I have take pathname through

var pathname = window.location.pathname;

Now I have multiple tags

<ul>
<li><a href="/1">1</a>
<li><a href="/12">12</a>
<li><a href="/13">13</a>
<li><a href="/14">14</a>
</ul>

Now I want to find <a> with the pathname that I have extracted

I tried this

$("ul").find(pathname+" a").parent().css('background-color", "red");

I got error in console that invalid property /1, something like that. Can anyone help me out ?

Upvotes: 0

Views: 1243

Answers (4)

Code Spy
Code Spy

Reputation: 9954

Try this

HTML

<ul>
 <li><a href="/1">1</a>
 <li><a href="/12">12</a>
 <li><a href="/13">13</a>
 <li><a href="/14">14</a>
</ul>

JQuery

var pathname = "/13";
$("ul").find("a[href='"+pathname+"']").closest("li").css("background-color", "red");

enter image description here

Demo https://jsfiddle.net/ipsjolly/stdqgjcx/4/

Upvotes: 1

Osama
Osama

Reputation: 3040

$("ul").find('a href=["'+pathname+'"]').parent().css("background-color", "red");

Upvotes: 1

Govind Samrow
Govind Samrow

Reputation: 10179

Do it with each loop:

var pathname = window.location.pathname;
$("ul li a").each(function(){

   if($(this).attr('href') == pathname ){
      $(this).css('background-color", "red");
   }

})

Upvotes: 1

Beny
Beny

Reputation: 165

Hi May be you can try something like this, So if you will use proper selector and check if it contains the current path string.Hope this helps.

      <div>John Resig</div>
        <div>George Martin</div>
       <div>Malcom John Sinclair</div>
        <div>J. Ohn</div>

      <script>
       $( "div:contains('John')" ).css( "text-decoration", "underline" );
        </script>

Jquery Docs

Upvotes: 1

Related Questions