diff --git a/lib/index.js b/lib/index.js index 6b00ca9..30994fe 100644 --- a/lib/index.js +++ b/lib/index.js @@ -2,6 +2,7 @@ const Document = require('./document') const Node = require('./node') +const Nodes = require('./nodes') const Attribute = require('./attribute') const Text = require('./text') @@ -12,5 +13,6 @@ module.exports = { Document: Document, Attr: Attribute, Node: Node, + Nodes: Nodes, Text: Text } diff --git a/lib/nodes.js b/lib/nodes.js new file mode 100644 index 0000000..d359670 --- /dev/null +++ b/lib/nodes.js @@ -0,0 +1,60 @@ +'use strict' + +/** + * @class + * @memberof node-html-light + */ +class Nodes { + + /** + * Wrap a set of Nodes to get access to utility functions + * @param {Array} elems an array of nodes + * @returns {Node} a new Node + */ + static fromArray(elems) { + return new Nodes(elems) + } + + /** + * @constructor + * @private + * @description Do not use this method directly. Use one of the static helper methods instead. + * @param {Array} elems an array of nodes + * @returns {Nodes} a new object wrapping the given array of nodes + */ + constructor(elems) { + this._elements = elems + } + + /** + * Returns an array of nodes matching tag name and attributes + * @param {Object} element an object whos properties reflect the properties of the element we are looking for + * @param {Array} [attrs=empty] attrs an array of attributes + * @param {Number} [limit=Infinity] limit the max number of results + * @returns {Array} + */ + find(element, attrs, limit) { + let result = [] + + if (limit === undefined || limit === null) { + limit = Infinity + } + + for (let i = 0, n = this._elements.length; i < n; i++) { + const el = this._elements[i] + const foundElements = el.find(element, attrs, limit) + result = result.concat(foundElements) + const size = foundElements.length + + if (size >= limit) { + break + } else { + limit = limit - size + } + } + + return result + } +} + +module.exports = Nodes \ No newline at end of file