简体   繁体   中英

adding css class in <body> javascript

I am facing an issue in jquery, i want to add a css test class in body tag.

My code

(function($) {  

    if($("#root").length){
        $("#root").closest("body").addClass('co_queue_page'); //not working
    }

})(jQuery);
<div class="row">    //react code
 <div id="root">
  <div> 
   <header>
    <div class="container-fluid">...</div>
   </header>
  </div>
 </div>
</div>

what should i do? some help me help?

在此处输入图像描述

在此处输入图像描述

You don't need to use .closest() method, there is only one tag in HTML document, just do it by selecting the <body> directly:

 (function($) { if($("#root").length){ $("body").addClass('co_queue_page'); } })(jQuery);

To select the <body> element, using jQuery, you can use:

const element = $(document.body);
const element = $("body");

Then you can use .addClass() to add your custom class dynamically, like so:

element.addClass("co_queue_page");

jQuery fiddle working example

This can be also done without any jQuery, accessing the body DOM element through the document object:

const element = document.body;
element.classList.add("co_queue_page");

Vanilla JS fiddle working example

Please add the below code:

$("body").addClass("class_name");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM