1

I want to turn a span of text red when I click on a button. Why does the first set of code, with separate Javascript and HTML, not work... but the second set of code does?

FIRST SET (not working)

JAVASCRIPT:
    function focus()
    {
        getElementById('redder').style.color = '#ff0000';
    }

HTML:
    <button id="button1" onClick="javascript:focus()">cool</button>
    <span id="redder"> RED </span>

. . .

SECOND SET (working)

HTML:
    <button id="button1" onClick="getElementById('redder').style.color = '#ff0000';">cool</button>
    <span id="redder"> RED </span>
2
  • focus() is a native DOM function, you need to use some other name for your function. Commented Feb 17, 2013 at 9:11
  • and no need for the javascript: label Commented Feb 17, 2013 at 9:19

2 Answers 2

3
  1. change the name of click event handler from focus to something else;
  2. you need use document.getElementById()
<script>
     function changeColor()
        {
            document.getElementById('redder').style.color = '#ff0000';
        }
    </script>
    <body>
        <button id="button1" onClick="changeColor();">cool</button>
        <span id="redder"> RED </span>
    </body>
Sign up to request clarification or add additional context in comments.

Comments

1

When using non-inline JavaScript, you need to add the document scope:

document.getElementById('redder').style.color('#ff0000');

I think JavaScript does not need that scope when defined inline, but I can't find documentation on that quickly.

2 Comments

It is always safe to use document. and it will break in some browsers if not present, so just always use it.
Certainly JS does need the scope, there's no window.getElementById() method.

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.