Setting up an if statement with window.location.origin in JS

1k views Asked by At

I am looking to delete my navigation menu on the landing page of a site I am building. However, I can't figure out how to ONLY target that page. The way I do it with the other pages, is that I write (window.location.pathname.includes("/pathname")) when I want to target a specific page.

But if I want to target the origin (www.hostname.com) of the site, I can't seem to do it without deleting the nav menu on all other pages since they all share the same hostname.

This is the function I am trying to execute:

function landingPage() {
  if (window.location.origin === "www.something.com") {
    document.querySelector(".main-navigation").remove("#primary-menu");
    document.querySelector(".site-branding").remove(".custom-logo");
  }
}
3

There are 3 answers

0
Quentin On BEST ANSWER

If you want to target a specific page on a site, then you need to check location.href or location.pathname as you are doing for other pages.

The origin defines the entire site, not its homepage.

1
dwosk On

What if you combine window.location.origin with a window.location.pathname conditional?

window.location.pathname should return "/" if you are on the landing page and not a sub-page.

0
Saswata Pal On
function landingPage() {
  if (window.location.hostname === "www.something.com"  && window.location.pathname==="/") {
      /*Your Condition Comes here */
  }
}

window.location.hostname will return the hostname of your website. You can compare the hostname and write the required condition you want to add.

to know more click window location