简体   繁体   中英

Add class to body if url contains

Caldera forms plugin for wordpress returns a URL similar to the one below when an error occurs during submission of a form.

?cf_er=_cf_process_5e7a1d0c43fbe

How, using jQuery, could I add a class to the body if the url contains AT LEAST this part;

?cf_er

Many thanks in advance for any help offered.

use includes to check existence of string ?cf_er .

 const url = "?cf_er=_cf_process_5e7a1d0c43fbe"; if (url.includes('?cf_er')) { $(document.body).addClass('someclass'); }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Assuming you get the URL as a string returned from the "Caldera forms plugin":

   const url = caldera_forms_plugin();

   if (url.includes('?cf_er') {
      $('body').addClass(MY_CLASS_NAME);
   }

But you don't really need to use jQuery to add a class to body, just do:

    body.classList.add(MY_CLASS_NAME);

see this code: https://stackoverflow.com/a/5448635/11918234 ; it will return an object called params with all params. in your case you'll to check if params.cf_er is not null or undefined, if true you will add your class to the dom.

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