Home > OS >  Add a class to a page element contained in a particular url
Add a class to a page element contained in a particular url

Time:02-18

I want to create a class for the title bars of pages that contain a certain piece of url. My url is www.domainname.com/poste/XXX and I want to add the class only if the part after the .com contains only /poste/. I've seen examples for "contains this term" but it's not exactly what I'm looking for. The existing class for the title bar is: .fusion-page-title-bar Thanks in advance for the help and advice!

CodePudding user response:

to check if a url contains any string, do the following:

if(window.location.href.indexOf(".com/poste") > -1) {
       // do something
}

(checking if the index of a string is bigger than -1 is like asking if he is in there)

to conditonally add class:

element.classList.add("my-class");

combined it would be:

if(window.location.href.indexOf(".com/poste") > -1) {
       titleClass = document.querySelector(".your-title-class");
       titleClass.classList.add("conditionalClass");
}

*there are other solutions using jquery (like the one in @Wimanicesir comment), but it personaly prefer not using it :)

CodePudding user response:

If I understand your problem is that you want to check if the URL ends with /poste/.

You can use the string function endsWith().

  var url = window.location.href
  console.log('Current url: ', url)
  
  if (url.endsWith("js")) {
    console.log('The url ends with js');
  }

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith

  • Related