user715564
user715564

Reputation: 1690

How to make a change on all pages with a specific URL

I have a list or URLs that I need to add a body class to. The list of URLs are found in the queryStrings variable. Here is my current code:

    var myUrl = window.location.href;
    var queryStrings = ["www.site.com/test", "www.site.com/test2"];
    var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);

    if (allPresent == false) {

    } else {
        document.body.classList.add("module-ads");
    }

    function CheckIfAllQueryStringsExist(url, qsCollection) {
        for (var i = 0; i < qsCollection.length; i++) {
            if (url.indexOf(qsCollection[i]) == -1) {
                return false;
            }
        }
        return true;
    }

Right now, allPresent equals false even if I am on the page www.site.com/test.

Upvotes: 0

Views: 44

Answers (4)

UX Nomaan
UX Nomaan

Reputation: 432

You can use an array function .includes() to do your check. Otherwise, @gaetanoM answer is the answer you're looking for.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = queryStrings.includes(myUrl);

if (allPresent == false) {
  // do something
} else {
  document.body.classList.add("module-ads");
}

Upvotes: 0

Dan Oswalt
Dan Oswalt

Reputation: 2189

take a look at the window.location object, that will give you many other ways to match your url.

https://developer.mozilla.org/en-US/docs/Web/API/Location

href will return the protocol, so you could just tack on "https://" + to each href check, or you could use location.pathname or something.

Upvotes: 0

gaetanoM
gaetanoM

Reputation: 42054

Your CheckIfAllQueryStringsExist is wrong.

Change it to:

function CheckIfAllQueryStringsExist(url, qsCollection) {
    for (var i = 0; i < qsCollection.length; i++) {
        if (url.indexOf(qsCollection[i]) != -1) {
            return true;
        }
    }
    return false;
}

Upvotes: 2

Scott Marcus
Scott Marcus

Reputation: 65796

Your are checking the URL to see if it contains the array, which is backward.

Also, you don't need any loops here. Just check the array for the existence of the current URL and instead of an empty true branch to your first if statement, just reverse the test logic so that you can just have one branch.

var myUrl = window.location.href;
var queryStrings = ["www.site.com/test", "www.site.com/test2"];
var allPresent = CheckIfAllQueryStringsExist(myUrl, queryStrings);

if (allPresent) {
    document.body.classList.add("module-ads");
}

function CheckIfAllQueryStringsExist(url, qsCollection) {
  // Just return whether the array contains the url
  return qsCollection.indexOf(url) > -1;
}

Upvotes: 0

Related Questions