1

Pretty green on this. Any ideas why this works:

$('.myclass div').append(' <a ">HELLO WORLD</a>').click(this.function);

and this doesn't:

$('.myclass div').after(' <a ">HELLO WORLD</a>').click(this.function);

Thanks!

JSuar
  • 21,056
  • 4
  • 39
  • 83
River
  • 1,487
  • 3
  • 15
  • 25

1 Answers1

5

In both cases, you're adding the handler to the div that was originally selected. Because events bubble, the first one will still work even tough the handler is on the parent of the <a>.

If you want the a element after the div, you need to bind directly to the a.

You can use .insertAfter() instead to accomplish this...

$('<a>HELLO WORLD</a>').insertAfter('.myclass div').click(this.function);
  • 1
    Just in case, here's the difference between `.after()` and `.insertAfter()`: http://stackoverflow.com/questions/1908229/jquery-whats-the-difference-between-after-and-insertafter – JSuar Feb 15 '12 at 01:33
  • You can also use `end()` like `$('.myclass div').after(' HELLO WORLD').end().click(this.function);` – elclanrs Feb 15 '12 at 02:57
  • @elclanrs: Sort of. If you use `.end()` right there, you're still working with the original jQuery object from `$('.myclass div')`, so it appears as though `.end()` gives you the context, which in this case is the `HTMLDocument`, so that's what gets the `click` handler. –  Feb 15 '12 at 03:13