Skip to content

Commit

Permalink
Element.prototype.remove()
Browse files Browse the repository at this point in the history
  • Loading branch information
astro committed Mar 29, 2011
1 parent 9ef35a7 commit 8ae9b75
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
27 changes: 27 additions & 0 deletions lib/element.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,33 @@ Element.prototype.t = function(text) {
return this;
};

/*** Manipulation ***/

/**
* Either:
* el.remove(childEl);
* el.remove('author', 'urn:...');
*/
Element.prototype.remove = function(el, xmlns) {
var filter;
if (typeof el === 'string') {
/* 1st parameter is tag name */
filter = function(child) {
return !(child.is &&
child.is(el, xmlns));
};
} else {
/* 1st parameter is element */
filter = function(child) {
return child !== el;
};
}

this.children = this.children.filter(filter);

return this;
};

/*** Serialization ***/

Element.prototype.toString = function() {
Expand Down
21 changes: 21 additions & 0 deletions test/test_element.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,5 +26,26 @@ vows.describe('ltx').addBatch({
var e = new ltx.Element('e').t('1 < 2').root();
assert.equal(e.toString(), '<e>1 &lt; 2</e>');
}
},

'remove': {
'by element': function() {
var el = new ltx.Element('e').
c('c').c('x').up().up().
c('c2').up().
c('c').up();
el.remove(el.getChild('c'));
assert.equal(el.getChildren('c').length, 1);
assert.equal(el.getChildren('c2').length, 1);
},
'by name': function() {
var el = new ltx.Element('e').
c('c').up().
c('c2').up().
c('c').up();
el.remove('c');
assert.equal(el.getChildren('c').length, 0);
assert.equal(el.getChildren('c2').length, 1);
}
}
}).run();

0 comments on commit 8ae9b75

Please sign in to comment.