'Onclick function error, function isn't defined

Over the recent days 've been trying to make buttons that changes a text's color by using

document.querySelector.('class name').style.color

in a function while using onclick to put that function in the button, but it always says my function *chanageColor isn't defined. Could some of you help me please? It also says theres an unexpected token, please help me with that as well!

<body>
    <div class="box">
      <h1> Hello</h1>
    </div>
       <script>
function changeColor(){
  document.querySelector.('.box').style.color = 'pink';
}
    </script>
    <button class="pink">Pink</button>
  </body>
</html>


Solution 1:[1]

Well, there's nothing in your code here that would even try to call your function so I can't say for sure what your issue is, but to hook up the click event of the button to your function, you use: .addEventListener().

Now, you do have a typo:

document.querySelector.('.box') // <-- The dot before ( is wrong

And your script element should be the last thing before you close the body tag so that by the time the script runs, all the HTML will have been parsed into memory.

<div class="box">
  <h1> Hello</h1>
</div>
<button class="pink">Pink</button>
 
<script>
  document.querySelector("button.pink").addEventListener("click", changeColor);
  function changeColor(){
    document.querySelector('.box').style.color = 'pink';
  }
</script>

And while this works, inline styles should be avoided whenever possible because they are the hardest type of CSS styling to override and lead to duplication of code. Instead, use CSS classes whenever you can (almost always) as shown here:

.pinkText { color:pink; }
<div class="box">
  <h1> Hello</h1>
</div>
<button class="pink">Pink</button>
 
<script>
  // Get your DOM element references just once, not every time the function runs:
  const box = document.querySelector('.box');
  document.querySelector("button.pink").addEventListener("click", changeColor);
  function changeColor(){
    box.classList.add('pinkText');
  }
</script>

Solution 2:[2]

<!DOCTYPE html>
<html>
<body>
    <div class="box">
      <h1> Hello</h1>
    </div>
    <button class="pink" onclick="changeColor()">Pink</button>
  </body>
       <script>
function changeColor(){
  document.querySelector('.box h1').style.color = 'pink';
}
    </script>
</html>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Radhey