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
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):Well, for one thing you have a quoting error:
should be:
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: