Tim Dickinson
Tim Dickinson

Reputation: 33

JavaScript: change style of element specified by class

I've tried my best to solve my own problem but am having trouble getting started with a fairly simple JS script.

I'm trying to change the font colour of text which contains the "-" character for a specified element class.

This is what I've got:

<html>
<body>
<script>
<!--
function myFunction()
{
var elements = document.getElementsByClassName("example");

for(var i = 0, length = elements.length; i < length; i++)
{
    if(elements[i].textContent.indexOf('-') != -1)
        {
            elements[i].style.color = red;
        }
    } 
}
-->
</script>
<table>
    <tr>
        <td class="example">-100<td>
        <td class="example">100<td>
    </tr>
</table>
</body>
</html>

What have I done wrong?

Edit: this is the final code I went with, which works perfectly well.

<!DOCTYPE html>
<html>
<body>

<script type="text/javascript">
<!--
function myFunction()
{
    var elements = document.getElementsByClassName("example");

    for(var i = 0, length = elements.length; i < length; i++)
    {
        if(elements[i].textContent.indexOf('-') !== -1)
            {
                elements[i].style.color = "red";
            } else
            {
                elements[i].style.color = "green";
            } 
    } 
}
-->
</script>

<table>
<tr>
<td class="example">-100<td>
<td class="example">100<td>
</tr>
</table>
<script type="text/javascript">
<!--
myFunction();
-->
</script>
</body>
</html>

Upvotes: 2

Views: 990

Answers (2)

Jobayer
Jobayer

Reputation: 1231

You have not called your js function & use elements[i].textContent.indexOf('-') === 0 instead of your current code. complete code for you -

function myFunction()
{
var elements = document.getElementsByClassName("example");

for(var i = 0, length = elements.length; i < length; i++)
{

if(elements[i].textContent.indexOf('-') === 0)
    {

        elements[i].style.color = "red";
    }
 } 
 }

</script>
<table>
<tr>
    <td class="example">-100<td>
    <td class="example">100<td>
</tr>
</table>

Upvotes: 0

Troy Gizzi
Troy Gizzi

Reputation: 2520

I believe there are a total of three mistakes here:

  1. Not calling the function at all. That can be taken care of like so:

    <body onload="myFunction();">

  2. Incorrect use of indexOf. Here's the right way:

    if(elements[i].textContent.indexOf('-') !== -1)

  3. Not quoting the color literal. Put red in quotes.

    elements[i].style.color = "red";

Upvotes: 4

Related Questions