From de1034273c0aa6897014dbfb6c6c92d809fd0556 Mon Sep 17 00:00:00 2001 From: =?utf8?q?Aleksander=20=C5=81ukasz?= Date: Tue, 19 Nov 2013 11:25:22 +0100 Subject: [PATCH] smartxml: node.unwrap --- src/smartxml/smartxml.js | 20 ++++++++++++++++++++ src/smartxml/smartxml.test.js | 13 +++++++++++++ 2 files changed, 33 insertions(+) diff --git a/src/smartxml/smartxml.js b/src/smartxml/smartxml.js index 0dd7082..c176f08 100644 --- a/src/smartxml/smartxml.js +++ b/src/smartxml/smartxml.js @@ -36,6 +36,10 @@ $.extend(DocumentNode.prototype, { this._$ = $(nativeNode); }, + isRoot: function() { + return this.document.root.sameNode(this); + }, + detach: function() { var parent = this.parent(); this._$.detach(); @@ -245,6 +249,22 @@ $.extend(ElementNode.prototype, { }; }, + /** + * Removes parent of a node if node has no siblings. + */ + unwrap: function() { + if(this.isRoot()) { + return; + } + var parent = this.parent(), + grandParent; + if(parent.contents().length === 1) { + grandParent = parent.parent(); + parent.unwrapContent(); + return grandParent; + } + }, + wrapText: function(params) { return this.document._wrapText(_.extend({inside: this}, params)); }, diff --git a/src/smartxml/smartxml.test.js b/src/smartxml/smartxml.test.js index 2666ae2..09fdfeb 100644 --- a/src/smartxml/smartxml.test.js +++ b/src/smartxml/smartxml.test.js @@ -302,6 +302,19 @@ describe('smartxml', function() { expect(node.contents()[2].getText()).to.equal(' a cat!'); }); + it('unwrap single node from its parent', function() { + var doc = getDocumentFromXML('
'), + div = doc.root, + a = div.contents()[0], + b = a.contents()[0]; + + var parent = b.unwrap(); + + expect(parent.sameNode(div)).to.equal(true, 'returns new parent'); + expect(div.contents()).to.have.length(1, 'root contains only one node'); + expect(div.contents()[0].sameNode(b)).to.equal(true, 'node got unwrapped'); + }); + describe('Wrapping text', function() { it('wraps text spanning multiple sibling TextNodes', function() { var section = elementNodeFromXML('
Alice has a small cat
'), -- 2.20.1