JQuery - If the url matches href, then move the LI to the beginning of UL?

It was an attempt to get this to work unsuccessfully. Any help would be appreciated.

Search for UL if any href is equal to the current URL, then move it to the top of the UL list stack.

var url = window.location.toString(); $('#partnerCharities li.panel h1 a').each(function(){ var myHref= $(this).attr('href'); if( url.match( myHref)) { $(this).parent().parent().parent().before("#slider1 li:first"); } }); 

This is a dynamically created list (image gallery), so not sure why jQuery is not working? This is the rough outline you see in Firebug ...

 <ul id="slider"> <li class="panel cloned"></li> <li class="panel"> <article> <h1><a href="site.com">Example</a></h1> </article> </li> <li class="panel cloned"></li> </ul> 
+2
source share
2 answers

There are a few errors with your code, look at the working example that I made.

Jsfiddle

HTML:

 <ul id="slider"> <li class="panel cloned">test1</li> <li class="panel"> <article> <h1><a href="site.com">This should come out on top.</a></h1> </article> </li> <li class="panel cloned">test2</li> </ul> 

JS:

 var url = "site.com"; //or window.location.toString(); $('#slider li.panel h1 a').each(function(){ var myHref= $(this).attr('href'); if( url == myHref) { $(this).closest("li").prependTo("#slider"); } }); 
+2
source

Even if your question doesn't really talk about this, I'm going to assume that you want it to match part of the href path of the current location .

If so, and hrefs will not have any query string parameters, you should do something like this:

  // get the pathname portion of the location var path = window.location.pathname; // get the <a> element whose href ends with the pathname, then get its <li> var $currentLi = $('#partnerCharities li.panel h1 a[href$=' + path + ']').closest('li'); // prepend the <li> to the parent of the <li> (which is the <ul>) $currentLi.prependTo( $currentLi.parent() ); 

Example: http://jsbin.com/owuye4/2/

The point is that you probably don't need to iterate over each element.

0
source

Source: https://habr.com/ru/post/1438210/


All Articles