admin管理员组

文章数量:1317894

If OS is MAC I set a variable & then on condition I want to add new class in body tag. Here is my code

<script type="text/javascript" language="javascript">
var mac=0;
    if(navigator.userAgent.indexOf('Mac') > 0){
        mac=1;
    }else{
        mac=0;
    }

if(1==mac){
    //document.body.className+='mac-os';
    //document.getElementsByTagName('body')[0].className+='mac-os';
    $('body').addClass('mac-os');
}else{
    //document.body.className+='win-os';
    //document.getElementsByTagName('body').className+='win-os';
    //$('body').addClass('mac-os');
    //$("body.className").addClass('win-os');
    //document.body.className += " " + 'win-os';
    $("body").addClass('win-os');
}
</script>

I have tried all but fail.

If OS is MAC I set a variable & then on condition I want to add new class in body tag. Here is my code

<script type="text/javascript" language="javascript">
var mac=0;
    if(navigator.userAgent.indexOf('Mac') > 0){
        mac=1;
    }else{
        mac=0;
    }

if(1==mac){
    //document.body.className+='mac-os';
    //document.getElementsByTagName('body')[0].className+='mac-os';
    $('body').addClass('mac-os');
}else{
    //document.body.className+='win-os';
    //document.getElementsByTagName('body').className+='win-os';
    //$('body').addClass('mac-os');
    //$("body.className").addClass('win-os');
    //document.body.className += " " + 'win-os';
    $("body").addClass('win-os');
}
</script>

I have tried all but fail.

Share Improve this question edited Jul 23, 2013 at 7:10 ilyes kooli 12.1k14 gold badges54 silver badges81 bronze badges asked Jul 23, 2013 at 7:06 PHP FerrariPHP Ferrari 15.7k27 gold badges86 silver badges150 bronze badges 6
  • Console says mac is 1? – Ivan Chernykh Commented Jul 23, 2013 at 7:07
  • Are all this happening when DOM is ready? – Ivan Chernykh Commented Jul 23, 2013 at 7:09
  • Did you get javascript errors ? Is jquery and your CSS included ? $('body').addClass('mac-os') should work. – Florent Commented Jul 23, 2013 at 7:13
  • @JonathanLonowski in my answer I was going to propose that making it the last thing in the <body> but I've not had a chance to test whether the <body> element is inserted into the DOM while it's still being constructed. – Alnitak Commented Jul 23, 2013 at 7:13
  • Sidenote: Instead of className, you should use classList. – Christoph Commented Jul 23, 2013 at 7:14
 |  Show 1 more ment

5 Answers 5

Reset to default 4

It's likely that the body element simply doesn't exist at the point your current code is being executed.

Ensure that your code is not executed until the DOM is ready, by putting it inside a ready handler:

$(document).ready(function() {
    // your code
    ...
});

It would also work if you put it inside the <body> element, typically at the end of the page.

If your script is in head your should wait until the body to be loaded, Change your code to:

$(document).ready(function(){
var mac=0;
    if(navigator.userAgent.indexOf('Mac') > 0){
        mac=1;
    }else{
        mac=0;
    }

if(1==mac){
    //document.body.className+='mac-os';
    //document.getElementsByTagName('body')[0].className+='mac-os';
    $('body').addClass('mac-os');
}else{
    //document.body.className+='win-os';
    //document.getElementsByTagName('body').className+='win-os';
    //$('body').addClass('mac-os');
    //$("body.className").addClass('win-os');
    //document.body.className += " " + 'win-os';
    $("body").addClass('win-os');
}
});

Or put your script into body tag:

<body>
<!-- your script -->
<!-- others -->
</body>

The html elements don't exist until after the page loads, but your js is executing before the <body> tag is even read by the browser. Your script tags e before the <body> tag, so the browser executes the js code first. If you need to delay execution of your js code until after the page loads(as is the case with most js code)--and you don't want to use jquery--then you can do this:

<script type="text/javascript">

window.onload = function() {

   //js code here

}

</script>

That function will not execute until the onload event occurs, which is after the page loads. The problem with the onload event is that all the images must load pletely before the event fires, and that can take a long time, which will delay rendering any styles set by the js, or allowing buttons to fire onclick handlers set by the js.

As an alternative, you can put your script tags just before the closing body tag: ...

<script type="text/javascript">

  //js code here

</script>

</body>

In that case, all the html on the page will have been parsed by the browser when the javascript tags are encountered, and as a result all the html elements will exist. <img> tags that are parsed will exist, but the browser doesn't wait for them to load--the browser continues on and parses the rest of the html while the images are loading. Even the body element exists even though its closing tag hasn't been seen yet.

Better still is to link to a js file, so that your js code isn't cluttering up the html:

<script type="text/javascript" src="myjs.js"></script>
</body>

Also, if you have this:

<body class="bgcolor">

...and your js code does this:

document.getElementsByTagName('body')[0].className += 'mac-os';

...then you will get his:

<body class="bgcolormac-os">

...which is not what you want. You need to add a space in there:

     ....    += ' mac-os';

...so that you get:

<body class="bgcolor mac-os">

A ment on your code style: you need to add more spaces, for instance:

if (1 == mac) {
  document.getElementsByTagName('body')[0].className += 'mac-os';
}
else {
  document.getElementsByTagName('body')[0].className += 'win-os';
}

Also, don't use 'cuddled' else clauses--they are really ugly. Consider using the style in the example where the else starts on a new line. Code clarity is what you are aiming for--not the fewest number of bytes. You might also consider indenting just 2 spaces--js statements can get pretty long, so conserving space there can be helpful.

And to avoid having to re-type those long document.get.... statements and make your code easier to read, you can do thing things like this:

   var mybody = document.getElementsByTagName('body')[0];

   if (1 == mac) {
      mybody.className += ' mac-os';
    }
    else {
      mybody.className += ' win-os';
    }

Your code works, maybe you forgot to wrap your code with

$(function () {
  //your code
}); 

?

$(function () {
    var mac = 0;
    if (navigator.userAgent.indexOf('Mac') > 0) {
        mac = 1;
    } else {
        mac = 0;
    }

    if (1 == mac) {
        //document.body.className+='mac-os';
        //document.getElementsByTagName('body')[0].className+='mac-os';
        $('body').addClass('mac-os');
    } else {
        //document.body.className+='win-os';
        //document.getElementsByTagName('body').className+='win-os';
        //$('body').addClass('mac-os');
        //$("body.className").addClass('win-os');
        //document.body.className += " " + 'win-os';
        $("body").addClass('win-os');
    }
});

Just put your jquery codes in $(document).ready(...) block to be sured that they execute in correct time...:

$(document).ready(function() {
    // jquery codes...
    $(document.body).addClass('your-class');
    // ...
});

本文标签: jqueryJavascript add new class in body tagStack Overflow