laurence keith albano
laurence keith albano

Reputation: 1482

How to add class on body tag if it contains hierarchical url?

This might be a simple question. How do I add a class to my body tag if the url is hierarchical?

For example: I have a url:

/coding/product/business-account/

I want to add a class to all sub urls under product only.

I'm using this script code, but I think the regex is only getting the first url path on it. Is there any tweak to only just add the class under /coding/product/ url?

<script type="text/javascript">
    // jQuery is passed to the ready function as a parameter, so we alias it with $
    // This will work for you even with wikispaces
    jQuery(function($){
        var loc = window.location.pathname.match(/^\/?(\w+)\b/);
        console.log(loc);
        if(loc) $(document.body).addClass(loc[1].toLowerCase());
    });
</script>

Upvotes: 1

Views: 41

Answers (1)

Sakil
Sakil

Reputation: 652

let regex = /(?<=\/product\/)(.*)/;
let loc = regex.test(`/coding/product/business-account/`);  //regex.test(window.location.pathname)
console.log('url matched: ' + loc)
if(loc) {
    //add class to element
}

Upvotes: 1

Related Questions