jimeast
jimeast

Reputation: 277

need to add a class to an element

here's my code:

<body>
<header>
<h1>Html quiz</h1>
</header>
<article>
<h2>What color is this?&nbsp;&nbsp; #00ff00

<ul>
    <li>
    <input type="radio" name="color1" id="red" />&nbsp;&nbsp;red
    </li>
    <li>
    <input type="radio" name="color1" id="green" />&nbsp;&nbsp;green
    </li>
    <li>
    <input type="radio" name="color1" id="blue" />&nbsp;&nbsp;blue
    </li>
    <li>
    <input type="radio" name="color1" id="teal" />&nbsp;&nbsp;teal
    </li>
    <li>
    <input type="submit" name="submit" value="Submit" onClick="fsubmit()" />
    </li>
</ul>
</article>
<div id="result"> </div>
<script>
function fsubmit() {
var answer = document.getElementById("green");
var result = document.getElementById("result");
if(answer.checked == true) {result.innerHTML="correct!";} else {result.class="red";  result.innerHTML="wrong";}
}
</script>
</body>

It's the first bit of code result.class="red" does nothing and the debugging console on chrome doesn't indicate a problem.

Upvotes: 1

Views: 80

Answers (5)

Trevor Oke
Trevor Oke

Reputation: 321

Try using setAttribute on the result:

result.setAttribute("class","red");

Upvotes: 0

Joeytje50
Joeytje50

Reputation: 19112

You can use result.className = 'red';, but you can also use result.classList.add('red');. The .classList.add(str) way is usually easier if you need to add a class in general, and don't want to check if the class is already in the list of classes.

Upvotes: 5

Alex Navasardyan
Alex Navasardyan

Reputation: 536

You probably need something like:

result.className = 'red';

In pure JavaScript you should use className to deal with classes. jQuery has an abstraction called addClass for it.

Upvotes: 0

Windwaker
Windwaker

Reputation: 111

You are missing a closing h2 tag. It should be:

<h2><!-- Content --></h2>

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You should be using className

result.className = "red"

Upvotes: 2

Related Questions