From 88ae6366f333e9fa997506d0961045dc5a6e4516 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20B=C3=B6hm?= Date: Tue, 22 Dec 2020 21:09:26 +0100 Subject: [PATCH] fix(replaceWith): Fix replacing element with itself (#1581) Fixes #962 --- lib/api/manipulation.js | 5 ++++- test/api/manipulation.js | 10 ++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/lib/api/manipulation.js b/lib/api/manipulation.js index 2f5ba87b22..d17f0dda1a 100644 --- a/lib/api/manipulation.js +++ b/lib/api/manipulation.js @@ -646,7 +646,10 @@ exports.replaceWith = function (content) { // Completely remove old element uniqueSplice(siblings, index, 1, dom, parent); - el.parent = el.prev = el.next = null; + + if (dom.indexOf(el) < 0) { + el.parent = el.prev = el.next = null; + } }); return this; diff --git a/test/api/manipulation.js b/test/api/manipulation.js index 27850409dd..2bf629635b 100644 --- a/test/api/manipulation.js +++ b/test/api/manipulation.js @@ -1391,6 +1391,16 @@ describe('$(...)', function () { expect($.html($src)).to.equal('

hi
here

'); }); + it('(self) : should be replaced after replacing it with itself', function () { + var $ = cheerio.load('foo', null, false); + var replacement = 'bar'; + $('a').replaceWith(function (i, el) { + return el; + }); + $('a').replaceWith(replacement); + expect($.html()).to.be.equal(replacement); + }); + it('(str) : should accept strings', function () { var $src = $('

hi there

'); var newStr = '
here
';