D
D
danilx5562021-10-10 18:46:45
AJAX
danilx556, 2021-10-10 18:46:45

How to attach a handler to a dynamic element?

The user enters the platform with an online lesson, at a certain moment he has a button.

In this button, you need to pull up the location.search value, I did it. But when entering the page, the user does not have this element with a button. He will appear at an unknown time.

I read that you can somehow delegate the handler to the parent, but did not find how to do it.

DOM before the button appears:
616309fd9953d623109299.png

DOM after the button appears:
616309e961859920014169.png

As code:

<div id="files" class="files panelitem mainbg" style="display:none;"></div>


Tell me how to hang a handler on an element that does not know when it will appear. So that when it appears, a certain function changes in the href button

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Aetae, 2021-10-10
@Aetae

And what about the event handler, if you need to change href immediately, and not at some event?
The correct answer is: find the function that adds this button and add a href change to it.
Bad answer: MutationObserver .

N
Nadim Zakirov, 2021-10-11
@zkrvndm

You have to stupidly hang the handler on the body.

W
writer_2159, 2021-10-12
@writer_2159

Event delegation.
you weigh the event on the parent and check that the click was on the desired element
https://learn.javascript.ru/event-delegation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question