skip to Main Content

this should be fairly simple for those of you who understand jQuery.

I am trying to get this script to run ONLY if <span class="site-header__cart-indicator "></span> is present on the loaded page.

Here is the untouched jQuery code:

window.setTimeout(redirectCheckout, 2000);

function redirectCheckout() {
  if (!(window.location.href.includes("?1"))) {
    window.location.href = "https://www.example.com/checkout";
  }
}

So here is my version of the code but it doesn’t seem to be working:

if (!(window.location.includes("<span class="
    site - header__cart - indicator "></span>")))
  window.setTimeout(redirectCheckout, 2000);

function redirectCheckout() {
  if (!(window.location.href.includes("?1"))) {
    window.location.href = "https://www.example.com/checkout";
  }
}

Can anyone tell me why my code isn’t working? What would be the correct code?

2

Answers


  1. To check if an element exists in the page you can select it then check the length property (if using jQuery) or if it’s null (if using plain JS):

    // jQuery
    if ($('.site-header__cart-indicator').length)
      window.setTimeout(redirectCheckout, 2000);
    
    // plain JS
    if (window.querySelector('.site-header__cart-indicator'))
      window.setTimeout(redirectCheckout, 2000); 
    
    Login or Signup to reply.
  2. Well, for one thing you have a quoting error:

    "<span class="site-header__cart-indicator"></span>"
    

    should be:

    '<span class="site-header__cart-indicator"></span>'
    

    But more to the point, this condition makes no sense. That string would never be in the location (the current URL). It would be on the page.

    Even though your code currently has no jQuery, you do specifically request its use. In which case you can select for that element and see if there are any matches. Something like this:

    if ($('span.site-header__cart-indicator').length > 0)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search