From: Aleksander Ɓukasz Date: Wed, 27 Nov 2013 09:39:43 +0000 (+0100) Subject: smartxml: handle insertAtIndex when index out of range X-Git-Url: https://git.mdrn.pl/fnpeditor.git/commitdiff_plain/b3232067c8388b27b1f92a3a188a854e3fe6a2fd?ds=sidebyside smartxml: handle insertAtIndex when index out of range --- diff --git a/src/smartxml/smartxml.js b/src/smartxml/smartxml.js index cfe94f0..e3c831d 100644 --- a/src/smartxml/smartxml.js +++ b/src/smartxml/smartxml.js @@ -274,8 +274,10 @@ $.extend(ElementNode.prototype, { insertAtIndex: function(nativeNode, index) { var contents = this.contents(); - if(contents[index]) { + if(index < contents.length) { return contents[index].before(nativeNode); + } else if(index === contents.length) { + return this.append(nativeNode); } }, diff --git a/src/smartxml/smartxml.test.js b/src/smartxml/smartxml.test.js index 98d7f88..e045788 100644 --- a/src/smartxml/smartxml.test.js +++ b/src/smartxml/smartxml.test.js @@ -346,6 +346,17 @@ describe('smartxml', function() { expect(b.getIndex()).to.equal(2, 'b node shifted right'); }); + it('appends node when inserting node at index out of range', function() { + var doc = getDocumentFromXML('
'); + + var test1 = doc.root.insertAtIndex({tagName: 'test1'}, 0), + test2 = doc.root.insertAtIndex({tagName: 'test1'}, 10); + + expect(doc.root.contents()[0].sameNode(test1)).to.equal(true, 'inserting at index 0 of empty nodes appends node'); + expect(doc.root.contents().length).to.equal(1, 'inserting at index out of range does nothing'); + expect(test2).to.equal(undefined, 'inserting at index out of range returns undefined'); + }); + it('appends element node to another element node', function() { var node1 = elementNodeFromParams({tag: 'div'}), node2 = elementNodeFromParams({tag: 'a'}),