user715564
user715564

Reputation: 1690

Add body class to list of pages based on URL

I would like to add a body class to a list of pages that have a specific URL. For example, if the URL is /page1.html, /page2.html, /page3.html, /page4.html etc. etc. I would like to add a class to the body tag.

The code I have works but it's very bloated. Is there a way to write this more elegantly? All in all, I will need to check 10 different URLs.

(function($) {
    if ( document.location.href.indexOf('page1.html') > -1 ||
         document.location.href.indexOf('page2.html') > -1 || 
         document.location.href.indexOf('page3.html') > -1 ||
         document.location.href.indexOf('page4.html') > -1 ) {
             $('body').addClass('testclass');
    }
}(jQuery));

It can be jQuery or vanilla JavaScript.

Upvotes: 0

Views: 237

Answers (4)

Samuel Gonçalves
Samuel Gonçalves

Reputation: 21

another way

const pages = ['page1.html', 'page2.html', 'page3.html', 'page4.html'];

$('body').addClass(pages.find(page => ($(location).attr('pathname').includes(page))) && 'testclass');

Upvotes: 0

deterjan
deterjan

Reputation: 390

I think the most elegant way to do this is to use Array.some()

(function($) {
    const pages = ['page1.html', 'page2.html' /* add whatever here */];

    if (pages.some(page => document.location.href.indexOf(page) > -1)) {
       $('body').addClass('testclass');
    }
}(jQuery));

Upvotes: 0

Shivratna Kumar
Shivratna Kumar

Reputation: 1311

You can do it like this:-

const pages = ['page1.html', 'page2.html', 'page3.html', 'page4.html'];

(function($) {
    pages.forEach(item => {
        if(document.location.href.indexOf(item) >=0)  {
            $('body').addClass('testclass');
        }
    });
}(jQuery));

Upvotes: 1

fdomn-m
fdomn-m

Reputation: 28611

Add the urls to an array and loop through the array:

var urls = ["page1.html", "page2.html", "page3.html", "page4.html"];
var href = document.location.href;
for (var i=0; i<urls.length; ++i) {
    if (href.indexOf(urls[i]) > -1)  {
      $('body').addClass('testclass');
    }
}

if the pages are all in the same format, just with a number, you could build them dynmically, but you have less control over adding/removing pages, eg:

var href = document.location.href;
for (var i=1; i<=4; ++i) {
    if (href.indexOf("page" + i + ".html") > -1)  {
      $('body').addClass('testclass');
    }
}

There are fancier ways of formatting these using array manipulations, but the concept is the same.

Upvotes: 0

Related Questions