How to add a class to body tag?

后端 未结 7 1000
猫巷女王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:14

    Well, you're going to want document.location. Do some sort of string manipulation on it (unless jQuery has a way to avoid that work for you) and then

    $(body).addClass(foo);
    

    I know this isn't the complete answer, but I assume you can work the rest out :)

    0 讨论(0)
  • I had the same problem,

    <body id="body">
    

    Add an ID tag to the body:

    $('#body').attr('class',json.class); // My class comes from Ajax/JSON, but change it to whatever you require.
    

    Then switch the class for the body's using the id. This has been tested in Chrome, Internet Explorer, and Safari.

    0 讨论(0)
  • 2020-12-09 02:20

    Something like this might work:

    $("body").attr("class", "about");
    

    It uses jQuery's attr() to add the class 'about' to the body.

    0 讨论(0)
  • 2020-12-09 02:27

    You can extract that part of the URL using a simple regular expression:

    var url = location.href;
    var className = url.match(/\w+\/(\w+)_/)[1];
    $('body').addClass(className);
    
    0 讨论(0)
  • 2020-12-09 02:29

    Use:

    $(document.body).addClass('about');
    
    0 讨论(0)
  • 2020-12-09 02:29
    $('body').toggleClass("className");
    

    perfectly works

    0 讨论(0)
提交回复
热议问题