Change text color with Javascript?

后端 未结 5 2094
执念已碎
执念已碎 2020-12-06 11:02

I want to change the color of a title when a button is clicked. This is my code, but it\'s not working and I can\'t figure out why not...

相关标签:
5条回答
  • 2020-12-06 11:42

    innerHTML is a string representing the contents of the element.

    You want to modify the element itself. Drop the .innerHTML part.

    0 讨论(0)
  • 2020-12-06 11:44
    <div id="about">About Snakelane</div>
    
    <input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
    <script>
    var about;   
    function init() { 
        about = document.getElementById("about");
        about.style.color = 'blue';
    }
    

    0 讨论(0)
  • 2020-12-06 11:50

    You set the style per element and not by its content:

    function init() { 
      document.getElementById("about").style.color = 'blue';
    }
    

    With innerHTML you get/set the content of an element. So if you would want to modify your title, innerHTML would be the way to go.

    In your case, however, you just want to modify a property of the element (change the color of the text inside it), so you address the style property of the element itself.

    0 讨论(0)
  • 2020-12-06 11:51

    use ONLY

    function init() { 
        about = document.getElementById("about");
        about.style.color = 'blue';
    }
    

    .innerHTML() sets or gets the HTML syntax describing the element's descendants., All you need is an object here.

    Demo

    0 讨论(0)
  • 2020-12-06 11:51

    Try below code:

    $(document).ready(function(){
    $('#about').css({'background-color':'black'});    
    });
    

    http://jsfiddle.net/jPCFC/

    0 讨论(0)
提交回复
热议问题