2

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>
3
  • .indexOf() is not being used properly It's a function call that takes a string and returns an integer. Commented Oct 13, 2014 at 3:59
  • if(elements[i].textContent.indexOf('-') != -1) Commented Oct 13, 2014 at 3:59
  • @TimDickinson have you also checked Troy Gizzi's answer? Commented Oct 13, 2014 at 4:09

2 Answers 2

4

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";

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

Comments

0

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>

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.