-2

I have the following jquery code:

$('.kv-editable-reset').addClass('green');

which should add the class 'green' to this element:

<button type="button" class="btn kv-editable-reset"></button>

but it does not work because .kv-editable-reset appears only later in the page, after click on the following button:

<button type="button" class="kv-editable-link"></button>

How can I detect elements that appears in the page only after another element has been clicked?

  • You could use a MutationObserver, but that's really a last resort. Do you have control over when the `kv-editable-reset` class is added to the element? Or is an event raised when it happens? If so, place your logic there. – Rory McCrossan Nov 14 '18 at 11:56
  • you could use `.delay(1000)` for 1sec delay on your function – Matt.S Nov 14 '18 at 11:57
  • @Matt.S what happens if the class is added 20 seconds later? Or if the class is added after 0.001s yet you make the user wait 1sec :) – Rory McCrossan Nov 14 '18 at 12:01
  • 1
    @OP Assuming this is for UI purposes only, then you could just put the CSS rules for `green` in to the .kv-editable-reset` class – Rory McCrossan Nov 14 '18 at 12:04
  • @aliengirl you mean `.kv-editable-reset` is dynamic button which appears after click of `.kv-editable-link` – Znaneswar Nov 14 '18 at 12:08
  • `delay()` only works on queued items. You can not use it to delay `addClass()` (unless you create your own queue). – Turnip Nov 14 '18 at 12:09

1 Answers1

0

Just listen to the click event for that button and then readdress adding the .green class.

By using .toggleClass('green', true) you don't even have to care about picking up pre-existing buttons and re-assign this class to them

$(() => {
  $('.kv-editable-link').on('click', function() {
    $("html").append(`<button type="button" class="btn kv-editable-reset">kv-editable-reset</button>`);
    $('.kv-editable-reset').toggleClass('green', true);
  });
});
.green{
  background-color: #0f0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="kv-editable-link">kv-editable-link</button>
Zze
  • 18,229
  • 13
  • 85
  • 118