JavaScript: DOM 'addEventListener()'

ยท

1 min read

intex.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>JavaScript</title>
    </head>
    <body>
        <h1>Click me!</h1>
        <script src="script.js"></script>
    </body>
</html>

script.js

const title = document.querySelector('h1');
title.addEventListener('click', () => {
    title.innerText = '๐Ÿ˜ƒ';
});
  • Get an event target

When you use querySelector with a class name, you should put a dot(.).

example) document.querySelector('.className')

  • Add 'addEventListener' API to the event target

  • Pass the call back function

Before click

image.png

After click

image.png