Jquery if url first pathname matches href then

this also applies to this other thread: jQuery - If the url matches href, then move the LI to the beginning of UL?

JQuery Code:

//set var to current url var url = window.location.toString(); //if url matches li anchor then bring it to the top of the list $('.nav li a').each(function(){ var myHref= $(this).attr('href'); if( url == myHref) { $(this).closest("li").prependTo(".nav"); } }); 

HTML is only found from Wordpress Navigation, so something like:

 <navrole="navigation"> <ul> <li> <a href=""> 

Navigation points to categories, and the URL matches href fine and the code works. But I can’t figure out how to get the code that will fire when I’m on the category’s child page, for example, when the URL:

 domain.com/category-name/child-page 

If I can get JQuery to detect only the first path outside the domain, then I will be golden. Everything that happened behind the first blank name can be omitted or configured as a wild card or something like that.

Any ideas?

+4
source share
3 answers

You can try using attribute contains selector :

 var dom = document.domain; var f = location.pathname.split('/')[1]; var url = dom + "/" + f; $('.nav li a[href*="'+url+'"]').closest("li").prependTo(".nav"); 
+2
source

I used this technique for my site. Here is how I did it:

 var Tabs = ["Tab1", "Tab2", "Tab3", "Tab4", "Tab5"]; var pathname = document.location.pathname; for (var i = 0; i < Tabs.length; i++) { //RegExp to check the name after first '/' var TabRE = new RegExp("^\/(" + Tabs[i] + ")"); if (TabRE.test(pathname)) { //Tab identified!!! } 

Or, if you just want to get the "first path outside the domain", you can simply do

 var path = (document.location.pathname).substring(1); var name; if (path.indexOf('/') >= 0) name = path.substring(0, path.indexOf('/')); else name = path; 
0
source

You will want to use the path to access everything after your domain name. Then split the string into slashes.

 var pathname = window.location.pathname; //"category-name/child-page" var path_components_arr = pathname.split("/"); //array containing components from above, in order. 

Then path_components gives you an array, each of which is part of the path between the slash. It looks like you only need the first element of this array ... I'm sure you can take it from there!

Hope this helps!

0
source

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


All Articles