Attach event to dynamic elements in JavaScript
Glossary overview

Attach event to dynamic elements in JavaScript

Я создаю элемент.

const promiseSetTimeOutPractice = () => {
	const section = document.querySelector('.section--promise');
	if (!section) return;

	createEl();

	el.addEventListener('click', () => console.log('click'));

	function createEl() {
		const el = document.createElement("div");
		el.innerText = "This is a dynamic element";
		section.appendChild(el);
	}


};

export default promiseSetTimeOutPractice;

Ошибка.

Причина – еременная el, на которую ты вешаешь обработчик, объявлена только внутри createEl(), поэтому она недоступна снаружи.

Чтобы повесить событие на динамически созданный элемент, нужно либо:

🔹 Вариант 1: Вернуть el из createEl():

const promiseSetTimeOutPractice = () => {
	const section = document.querySelector('.section--promise');
	if (!section) return;

	const el = createEl(); // !

	el.addEventListener('click', () => console.log('click'));

	function createEl() {
		const el = document.createElement("div");
		el.innerText = "This is a dynamic element";
		section.appendChild(el);
		return el; // !
	}


};

export default promiseSetTimeOutPractice;

🔹 Вариант 2: Вешать событие делегированно (на родителя):

const promiseSetTimeOutPractice = () => {
	const section = document.querySelector('.section--promise');
	if (!section) return;

	createEl();

	// Делегирование: слушаем клики на section и фильтруем по нужному классу
	section.addEventListener('click', (e) => {
		if (e.target.classList.contains('dynamic')) {
			console.log('Click on dynamic element');
		}
	});

	function createEl() {
		const el = document.createElement("div");
		el.classList.add('dynamic');
		el.innerText = "This is a dynamic element";
		section.appendChild(el);
	}
};

export default promiseSetTimeOutPractice;