直前に選択していた要素を現在の要素集合にマージさせる.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()
には引数を与えることでフィルタリングが可能になります。
以前選択していた要素集合をフィルタリングしてから現在の集合にマージします。