3

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!

3
  • I've never seen this syntax before :'D seems like you're confused between php and javascript Commented Mar 31, 2015 at 8:20
  • this reminds of Java scriptlet. Javascript is not Java, you cannot do something like that Commented Mar 31, 2015 at 8:23
  • Yeah, you guys are right. Dumb question ^^ But the answers below helped a lot in understanding how javascript works. Commented Mar 31, 2015 at 9:27

2 Answers 2

2

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>

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

Comments

0
<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.

Comments

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.