14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

《jQuery》3系で廃止になった.andSelf()のこと。

Posted at

直前に選択していた要素を現在の要素集合にマージさせる.andSelf()は、jQueryの3系から.addBack()メソッドに置き換わりました。

.andSelf()は .addBack()になった

例えば、任意のテキストを 一文字ずつspanで囲うスクリプトを書いてみました。


const spanText = (text) => {

  $(text).children().andSelf().contents().each(function() {

    if (this.nodeType == 3) {

      $(this).replaceWith($(this).text().replace(/(\S)/g, '<span>$1</span>'));

    }

  });

};
spanText('.js-span');

上は、下のようになります。


const spanText = (text) => {

  $(text).children().addBack().contents().each(function() {

    if (this.nodeType == 3) {

      $(this).replaceWith($(this).text().replace(/(\S)/g, '<span>$1</span>'));

    }

  });

};
spanText('.js-span');

.andSelf()と.addBack()の違い

.andSelf().addBack()の違いとしては.addBack()には引数を与えることでフィルタリングが可能になります。
以前選択していた要素集合をフィルタリングしてから現在の集合にマージします。

14
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?