admin管理员组

文章数量:1410724

I am trying to make an onclick button to change the background color of a div, using its id. My JavaScript function is as follows:

    function changeButton(color) {
      document.getElementById('button1').style.backgroundColor = color;
     }

and I'm linking to it in the HTML file like this:

    <script> src="websiteCleanJS.js" </script>
    .
    .
    .
    <div id='button1' onclick="changeButton('red')"> </div>

I am trying to make an onclick button to change the background color of a div, using its id. My JavaScript function is as follows:

    function changeButton(color) {
      document.getElementById('button1').style.backgroundColor = color;
     }

and I'm linking to it in the HTML file like this:

    <script> src="websiteCleanJS.js" </script>
    .
    .
    .
    <div id='button1' onclick="changeButton('red')"> </div>
Share Improve this question edited Mar 9, 2015 at 15:18 Mahmud Ahmad asked Mar 9, 2015 at 15:11 Mahmud AhmadMahmud Ahmad 1713 silver badges18 bronze badges 8
  • 4 <div id='button1', onclick('red')> – that is total nonsense and miles away from valid syntax. You need to go learn some basics. – C3roe Commented Mar 9, 2015 at 15:12
  • start from here, pleas: developer.mozilla/en-US/Learn/Getting_started_with_the_web/… – rvandoni Commented Mar 9, 2015 at 15:13
  • In an odd twist your JavaScript syntax is fine but your HTML is wrong. – j08691 Commented Mar 9, 2015 at 15:14
  • Accidentally copied it over wrong, sorry! @CBroe – Mahmud Ahmad Commented Mar 9, 2015 at 15:16
  • Your click syntax is still incorrect. Should be onclick="changeButton('red')" – j08691 Commented Mar 9, 2015 at 15:17
 |  Show 3 more ments

1 Answer 1

Reset to default 4

try this:

 <script src="websiteCleanJS.js"></script>
    .
    .
    .
    <div id='button1'  onclick="changeButton('red')"> </div>

本文标签: htmlChanging background color using JavaScript using idStack Overflow