0

Is there a way using javascript and HTML to change the color of a span? For example:

<span onLoad="document.getElementById('test').style.color = 'red';" id="test">test</span>

But that doesn't seem to work.

Quick update: This is just a precursor to the actual problem that I'm trying to solve. Basically I'm inside a CMS that only allows for in place HTML editing. That means that I don't have access to the head to add custom javascript functions etc. What I'm trying to do is make an inline function that takes the date specified (in a span for example) and then colorizes it based on some in-line js logic.

3
  • 8
    why aren't you using CSS?? Commented Dec 11, 2012 at 20:31
  • @js1568 This is just a precursor to the actual problem that I'm trying to solve. Basically I'm inside a CMS that only allows for in place HTML editing. That means that I don't have access to the head to add custom javascript functions etc. What I'm trying to do is make an inline function that takes the date specified (in a span for example) and then colorizes it based on some in-line js logic. Commented Dec 11, 2012 at 20:35
  • @bswinnerton You do know that the header is not the only place you can place script tags (in fact its generally recommended to place your script tags on the bottom of your page) Commented Dec 11, 2012 at 20:37

3 Answers 3

3

Spans do not have an "onload" event. If you want to run that when the page loads, add a script block on the <head> with the following code:

window.onload = function() {
    document.getElementById('test').style.color = 'red';
}

Considering your clarification about not having access to the header: you can add a <script> block anywhere below the elements you're targeting, and it works. If possible, add a single script block before </body> (or as far down as possible). Another possibility is just adding a class from the CMS editor, and define that class on an external CSS file. Yet another possibility are inline CSS styles, as suggested on defau1t's answer.

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

Comments

2

If you have any reason for not using css and want to use JavaScript then you can use

window.onload=function(){
    document.getElementById('test').style.color = 'red';
}

Comments

1

onload event is defined for body, not DOM elements. You can use document.getElementById("test").style.color = "red";

OR simple use:

<span id="test" style="color:red;">test</span>

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.