0

I made a simple function which print element in console before change a text color when I click the "Click me".

function addEventToTitle(){
    const title = document.getElementsByClassName("title")[0];
    title.addEventListener('click', changeColorOfTitle);
  }
  
  function changeColorOfTitle(){
    const title = document.getElementsByClassName("title")[0];
    console.log(title);
    title.style.color = "red";
  }
  
  addEventToTitle();
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script defer type="text/javascript" src="test.js"></script>
    <title>Document</title>
</head>
<body>
    <Button class="title">Click me</Button>
</body>
</html>

In snippet, It works like I expected. like below

<button class="title">Click me</button>

But, when I tried this in local. It always prints like this

<button class="title" style="color: red;">Click me</button>

The result should not imply style="color: red; because console.log is executed before change color.

Same code but different result, I don't know what is the reason for this.

BeGood
  • 1
  • 4

0 Answers0