1

I want to use each fn to append elements to all divs where id starts with post. How to do it right?

import $ from 'jquery'

export const fn = (): void => {
  const $posts = $('[id^="post_id_"]')
  if ($posts.length === 0) return

  $posts.append('<h1>123</h1>') //works

  $posts.each((idx, el) => {
    // here i need to do some staff

    this.append('<h1>321</h1>') // jQuery.Deferred exception: this.append is not a function TypeError
    el.append('<h1>321</h1>') // append as string - not html
  })
}
ZiiMakc
  • 31,187
  • 24
  • 65
  • 105
  • [Close](https://stackoverflow.com/questions/28733627/jquery-access-functions-from-an-each-loop), but not quite (despite the title)... – T.J. Crowder May 27 '20 at 14:19
  • 1
    @T.J.Crowder [This](https://stackoverflow.com/questions/6409039/jquery-each-this) one maybe? – Andreas May 27 '20 at 14:19
  • @Andreas wrapping this not working too... – ZiiMakc May 27 '20 at 14:21
  • 1
    @RTW I also missed that you're using an arrow function which "messes" with `this` in the callback of `.each()` – Andreas May 27 '20 at 14:23
  • 1
    @Andreas - I updated the accepted answer to your dupetarget so it covered using `this` or the second argument to the `each` callback. :-D – T.J. Crowder May 27 '20 at 14:23

1 Answers1

2

Within the each callback, this will be the same as it is outside the each callback because you're using an arror function, and el is a DOM element, not a jQuery object. If you want to use jQuery methods on the element, use $() on it:

$(el).append('<h1>321</h1>');
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875