Reputation: 469
I'm quite new to css / javascript so I'm sorry for this dumb question. I want to use a css class if the URL matches my criteria. My try:
<script>
if ((document.URL) == 'http://www.test.testsite.testtest.com/products/#') {
</script>
<div class="success">
content
</div>
<script>
}
else {
</script>
<div class="nosuccess">
content
</div>
<script>
}
</script>
The result: It just displays nothing. Probably a simple mistake, but as I said, I'm quite new to javascript.
Thanks for help!
Upvotes: 3
Views: 5178
Reputation: 308
<script>
if ((document.URL) == 'http://www.test.testsite.testtest.com/products/#') {
var node = document.createElement("div");
var textnode = document.createTextNode("content");
node.setAttribute("class", "success");
node.appendChild(textnode);
document.getElementById("div-id").appendChild(node);
}
else{
var node = document.createElement("div");
var textnode = document.createTextNode("content");
node.setAttribute("class", "nosuccess");
node.appendChild(textnode);
document.getElementById("div-id").appendChild(node);
}
</script>
You should not use direct HTML content in if else part of javascript, instead use javascript to append the desired output.
Upvotes: 0
Reputation: 10209
I recommend you to separate the HTML
from JavaScript
.
I added and id
(content) to the div that i want to change the class
. I make use of document.getElementById('content')
to get the tag that i want the class to be changed.
After I get the tag I want to change the class, to do that, make use of property .className
to change the class
.
Notes: Make sure that the script
tag is after the HTML
you want to change.
<div id="content">
content
</div>
<script>
if ((document.URL) == 'http://www.test.testsite.testtest.com/products/#') {
document.getElementById('content').className = "success";
} else {
document.getElementById('content').className = "nosuccess";
}
</script>
Upvotes: 2