5

Is there a way to add CSS styling that works only when a specific URL is loaded. I have a URL that has /service/ at the end. Only for this I want some CSS styling to work on a specific Div (myDiv). Is there a way? I cannot add an ID to the body tag of that service page. The page is backoffice generated.

2
  • 1
    The page is backoffice generated. what does that means? Commented Feb 21, 2017 at 12:20
  • if(this.href.substr(this.href.lastIndexOf('/') + 1) == 'service') {//your css styling through js} Commented Feb 21, 2017 at 12:22

3 Answers 3

3

url.match("/service/$") will match if the url endswith /service/ because $ means endWith in a .match()

Update: To get the url use: window.location.href.match("/service/$")

var url = "www.stackoverflow.com/questions/service/"
if (url.match("/service/$")) {
  $('#url').css("background-color", "yellow")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="url"> url </div>

Sign up to request clarification or add additional context in comments.

4 Comments

thanks. Is there a way to do the same but leaving out the: var url = "www.stackoverflow.com/questions/service/" ? So I don't have to specify the full URL path.
Sorry Carsten, but where do I place: window.location.href.match("/service/$")
any ways with css only?
@DanD. No that can't be done with css only
0

You can use the following:

if (window.location.href.indexOf('/service/') !== -1) {
  document.getElementById("myDiv").className += ' specialclass';
}

1 Comment

You code checks if the href contains /service/ and not if it endswith
0

Try with CSS only

[href$='home']{
    color : red;
}
<a href="something/home">home</a>
<a href="something/home/somethingelse">home</a>

2 Comments

How does this add a css style to an element if the url of the current page ends with a specific string?
ok my bad i misunderstood the question. Question is for the url of the page.I thought for a anchor tag

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.