I'm new to JS and I'm trying to perform onclick on a text in a external js file. This is my html
<!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.0" />
<title>Document</title>
</head>
<body>
<p class="p">
Use the HTML DOM to assign an "onclick" event to a p element:
</p>
<p class="demo">Click me to change the above text</p>
<script>
window.onload = startListen();
</script>
<script type="text/javascript" src="/1.js"></script>
</body>
</html>
My js file
function startListen() {
var demoElement = document.querySelector(".demo");
var pElement = document.querySelector(".p");
demoElement.onclick = function change() {
pElement.innerHTML = "Text is changed";
};
}
I want to click p.demo and the text in p.p will be changed but not working with external file. It still works with inline syntax with html attribute like this.
html
<p class="demo" onclick="change()">Click me to change the above text</p>
js
function change() {
var pElement = document.querySelector(".p");
pElement.innerHTML = "Text is changed";
}
I added onload but not work. Could u help me! Thanks