How to add a class to body tag?

后端 未结 7 1001
猫巷女王i
猫巷女王i 2020-12-09 02:08

I want to add a class to a body tag with jQuery.

For example if the URL is http://www.mywebsite.com/about_us.asp, I want add the first five letters, in this case \'a

相关标签:
7条回答
  • 2020-12-09 02:34

    This should do it:

    var newClass = window.location.href;
    newClass = newClass.substring(newClass.lastIndexOf('/')+1, 5);
    $('body').addClass(newClass);
    

    The whole "five characters" thing is a little worrisome; that kind of arbitrary cutoff is usually a red flag. I'd recommend catching everything until an _ or .:

    newClass = newClass.match(/\/[^\/]+(_|\.)[^\/]+$/);
    

    That pattern should yield the following:

    • ../about_us.html : about
    • ../something.html : something
    • ../has_two_underscores.html : has
    0 讨论(0)
提交回复
热议问题