trying to add a CSS class to aa parent item when the URL contains a directory path.
For instance if my url is
example.com/directory/about.html
I want to add a CSS class an item in my top navigation if it contains /directory/
in it.
so in this case, example.com/directory/overview.html
would get a CSS class " active-parent
"
which would be .main-nav li a.active-parent
(mind you I am already using jquery to check for teh URL and make that page active, but its when its a sub page of a section, the parent is not highlighted)
I thought I could usde the :contains() Selector
but I dont know how to apply it to a URL
jQuery selectors can't be used on an url. You must parse the url and check the content be yourself.
if (window.location.href.indexOf('/directory/') != -1) {
// Add a css class to a html element
}
You may want to do a more generic way be using the split function :
window.location.pathname.split('/').forEach(function(directory) {
if (directory == 'directory') {
// Add a css class to a html element
}
});
I f I understand you correctly, you want to filter through a group of urls and then, based on text within the href
, you want to manipulate data. In that case, use the .filter() function like so:
$("a").filter(function(i) { return $(this).attr("href").indexOf("document") > -1; })
This Grabs ALL A
tag elements, filters them using the function inside to determine if the href
has "document" in it or not. Then simply use the .each() function to do whatever, like so:
$("a")
.filter(function(i) { return this.href.indexOf("document") > -1; })
.each(function(i) {
$(this).parent().addClass("some-class-name");
});
If you need more understanding, just comment.
Based on limited information, I'd suggest:
$('a').filter(
function(){
return this.href.match(/(\/\w+\/)/);
}).parent().addClass('parent');
This assumes the class is added if the href
contains any directory, not simply a specific directory named 'directory'.
References:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.