Home > Enterprise >  How to hide an element if the page contains a specific url / word?
How to hide an element if the page contains a specific url / word?

Time:08-11

With JavaScript I'm trying to hide an element that contains a text message when the page URL is my-website.com/login/?lost_pass=1. I managed to hide the tag but it doesn't work as I expected.

The unwanted tag is actually hidden, but the same also happens when the page is my-website.com/login while it should only be hidden if the page is my-website.com/login/?lost_pass=1

So, for example, you are on my-website.com/login, but when you click "lost password" the page reloads to show a different form, so the URL becomes my-website.com/login/?lost_pass = 1

Can anyone help me with this? I don't understand where I'm wrong.

I tried this, but the tag is hidden on all pages

window.onload = function() {
  if (window.location.href.indexOf('?lost_pass=1')) {
    //Hide the element.
    document.querySelectorAll('#msg_social')[0].style.display = 'none';
  }
};

Then I tried that, but the tag is not hidden in any of the pages

if (window.location.href.indexOf("?lost_pass=1") != -1) {
$("#msg_social").hide();
}

CodePudding user response:

Your onl oad code has a if that always pass :

window.onload = function() {
  // this if will always pass, any number will pass that if like -1, 25 etc...
  if (window.location.href.indexOf('?lost_pass=1')) {
    //Hide the element.
    document.querySelectorAll('#msg_social')[0].style.display = 'none';
  }
};

it's better to use .contains :

window.onload = function() {
  if (!window.location.href.includes('?lost_pass=1')) {
    //Hide the element.
    document.querySelectorAll('#msg_social')[0].style.display = 'none';
  }
};

it's shorter and avoid forgetting about the != -1 thing

  • Related