Attach event to dynamic elements in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To attach event, use document.addEventListener() in JavaScript. Following is the code −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<link rel="stylesheet" href="//">
<script src=""></script>
<script src=""></script>
<input type="button" value="submit" id="buttonSubmit" />
      if( && 'buttonSubmit'){
         console.log("Event generation on the button click")

To run the above program, save the file name “anyName.html(index.html)” and right click on the file. Select the option “Open with Live Server” in VS Code editor.


This will produce the following output −

After clicking the submit button, the screenshot is as follows −

Updated on 11-Sep-2020 06:28:00