SBM
SBM

Reputation: 137

jQuery if Location.Pathname contains

I am currently using the following code to target individual pages such as http://my-website.com/about/

    if (document.location.pathname == "/about/") {
        //Code goes here
    }

I am wondering how to do the same for all pages that have a certain parent page such as /about/in the following examples..

http://my-website.com/about/child-page1

http://my-website.com/about/child-page2

Upvotes: 8

Views: 23532

Answers (4)

Auguste
Auguste

Reputation: 11

I like to use .includes:

if (document.location.pathname.includes('/about')) {
// your Code
}

Upvotes: 0

Sohail
Sohail

Reputation: 548

A bit neat picky but for future references it's safer to check against -1:

  if (document.location.pathname.indexOf('/about') > -1) {
    // your Code
  }

Upvotes: 0

marteljn
marteljn

Reputation: 6516

    if (document.location.pathname.indexOf("/about/") === 0) {
        //Code goes here
    }

This will check to make sure the pathname always starts with that string. If you are interested in checking the format more specifically, you will need to use regex.

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388316

use indexOf - it will test true for all pathnames starting with /about/

if (document.location.pathname.indexOf("/about/") == 0) {
    //Code goes here
}

Upvotes: 22

Related Questions