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!
Asked
Active
Viewed 644 times
0
-
1[How to check if the URL contains a given string?](https://stackoverflow.com/questions/4597050/how-to-check-if-the-url-contains-a-given-string) and [How to add a class to a given element?](https://stackoverflow.com/questions/507138/how-to-add-a-class-to-a-given-element) – Wimanicesir Feb 18 '22 at 09:45
-
@Wimanicesir Yes ! But how do I proceed for my application which is "contains only /poste/"? – Croquix Feb 18 '22 at 09:48
2 Answers
1
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 :)

Guy Nachshon
- 2,411
- 4
- 16
-
Both solutions provided in the comment are also without jQuery :) The first one has jQuery in it, but it's just used for the document ready. The important code is all vanilla JS. Even more, all the code you used here can be found back literately in those two posts. – Wimanicesir Feb 18 '22 at 15:05
0
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

Wimanicesir
- 4,606
- 2
- 11
- 30