xxxxxxxxxx
<script>
function myfunc() {
alert("hi!")
}
</script>
<button onclick="myfunc()">alert me</button>
xxxxxxxxxx
// Here you can use getElementById
// or getElementByClassName or getElementByTagName...
// Example #1
document.getElementById("button").onclick = function() {
alert("Hello World!");
}
// Example #2
let obj = document.getElementsByClassName('button');
obj.addEventListener("click", function() {
// your code here...
});
// Example #3 (getting attributes)
let obj = document.getElementById("button")
obj.onclick = function() {
obj.style.display = "none";
// or:
// obj.style = "display: none; color: #fff"
}
xxxxxxxxxx
var button = document.querySelector('button');
button.onclick = function() {
//do stuff
}
xxxxxxxxxx
// Select the element using its ID
var element = document.getElementById('myButton');
// Add the onclick event listener
element.onclick = function() {
// Code to be executed when the element is clicked
console.log('Button clicked!');
};
xxxxxxxxxx
<!DOCTYPE html>
//Note, this only works with a local script, it does not work if the HTML file
//is linked to an external js file
<html>
<body>
<h1>HTML DOM Events</h1>
<h2>The onclick Event</h2>
<h3 onclick="myFunction(this, 'red')">Click me to change my text color.</h3>
<h3 onclick="myFunction(this, 'green')">Click me to change my text color.</h3>
<h3 onclick="myFunction(this, 'blue')">Click me to change my text color.</h3>
<h3 onclick="myFunction(this, 'purple')">Click me to change my text color.</h3>
<script>
function myFunction(element, color) {
element.style.color = color;
}
</script>
</body>
</html>