Andrei Shcherbakov Andrei Shcherbakov - 3 months ago 8
CSS Question

javascript doesn't change color of span container

i'm trying to change my span's text color using

document.getElementById("indicator").style.color = "red";


and logs

console.log(document.getElementById("indicator").style.color);


tells me that it changes,but color still "black"

I'm using different css and bootstrap aswell in the project.
How can i fix this problem?

Answer

You need to make sure your script is being called after the DOM item has loaded. If using jQuery you can simply wrap your function inside a document ready tag like this:

$(function(){
document.getElementById("indicator").style.color = "red";
})

Fiddle:

https://jsfiddle.net/5jqhf7hz/

If you are using pure JavaScript you will need to make sure the script is listed after the DOM element. Putting the script at the end of your page should accomplish this.

Comments