Skip to content
This repository has been archived by the owner on Jan 6, 2025. It is now read-only.

Commit

Permalink
feat(nodes.js): add forEach method to allow iterating over nodes
Browse files Browse the repository at this point in the history
  • Loading branch information
stfsy committed Feb 11, 2017
1 parent ca17c01 commit 6d89c1c
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions lib/nodes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict'

const Node = require('./node')

/**
* @class
* @memberof node-html-light
Expand Down Expand Up @@ -55,6 +57,47 @@ class Nodes {

return result
}

/**
* Executes the callback function for every wrapped element and (optionally) for every wrapped elements children
* @param {Function} callback the callback to be invoked for every element
* @param {Boolean} [recursive=false] recursive flag to indicate if callback should be invoked for child elements, too
*/
forEach(callback, recursive) {
this._elements.forEach((element) => {

// iterating recursively we have to wrap the parser nodes with our node implementation
if (!(element instanceof Node)) {
element = Node.create(element)
}

const type = element.get().type
const whitespace = this._isWhitespace(element)
if ( type === Node.TYPE_TAG || type === Node.TYPE_COMMENT || !whitespace) {
callback(element)
}

if (recursive) {
const children = element.get().children
if (children && children.length) {
new Nodes(children).forEach(callback, recursive)
}
}
})
}

_isWhitespace(element) {
const type = element.get().type

if (type === 'text') {
const text = element.get().data
if (/^[\s\\n\\r]*$/.test(text)) {
return true
}
}

return false
}
}

module.exports = Nodes

0 comments on commit 6d89c1c

Please sign in to comment.