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.
-
1The page is backoffice generated. what does that means?Vilas Kumkar– Vilas Kumkar2017-02-21 12:20:39 +00:00Commented Feb 21, 2017 at 12:20
-
if(this.href.substr(this.href.lastIndexOf('/') + 1) == 'service') {//your css styling through js}Rahul– Rahul2017-02-21 12:22:02 +00:00Commented Feb 21, 2017 at 12:22
Add a comment
|
3 Answers
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>
4 Comments
Eddy
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.
Eddy
Sorry Carsten, but where do I place: window.location.href.match("/service/$")
Dan D
any ways with css only?
Carsten Løvbo Andersen
@DanD. No that can't be done with css only
You can use the following:
if (window.location.href.indexOf('/service/') !== -1) {
document.getElementById("myDiv").className += ' specialclass';
}
1 Comment
Carsten Løvbo Andersen
You code checks if the
href contains /service/ and not if it endswithTry with CSS only
[href$='home']{
color : red;
}
<a href="something/home">home</a>
<a href="something/home/somethingelse">home</a>
2 Comments
Carsten Løvbo Andersen
How does this add a css style to an element if the url of the current page ends with a specific string?
Ashish Kumar
ok my bad i misunderstood the question. Question is for the url of the page.I thought for a anchor tag