const button = document.createElement('button'); button.textContent = 'Click me'; document.body.appendChild(button); button.addEventListener('click', () => { console.log('Button clicked!'); }); // Simulate a click event button.click();
The button.click() method programmatically triggers the click event, so the event listener runs and logs 'Button clicked!'.
Event bubbling means the event starts at the target element and then moves up through its parent elements, triggering their event handlers in order.
const list = document.createElement('ul'); ['One', 'Two', 'Three'].forEach(text => { const li = document.createElement('li'); li.textContent = text; list.appendChild(li); }); document.body.appendChild(list); list.addEventListener('click', event => { console.log(event.target.textContent); }); // Simulate clicking the second list item list.children[1].click();
The event listener is on the ul, but event.target refers to the clicked li. Clicking the second li logs 'Two'.
const btn = document.createElement('button'); btn.id = 'myBtn'; btn.textContent = 'Click me'; document.body.appendChild(btn); btn.addEventListener('click', function() { this.classList.toggle; });
The code references this.classList.toggle without parentheses, so it does not call the function. No error is thrown, but no class is toggled.
<form id="myForm"> <input type="text" name="name" /> <button type="submit">Submit</button> </form> <script> const form = document.getElementById('myForm'); form.addEventListener('submit', event => { // What goes here? }); </script>
event.preventDefault() stops the browser's default action, such as submitting a form and refreshing the page. Other options do not prevent submission correctly.
