Skip to content

Instantly share code, notes, and snippets.

@franz-josef-kaiser
Last active March 2, 2017 10:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save franz-josef-kaiser/220afb38eac9c21fae31 to your computer and use it in GitHub Desktop.
Save franz-josef-kaiser/220afb38eac9c21fae31 to your computer and use it in GitHub Desktop.
JavaScript iterator garden – NodeIterator: a poor mans HTML scraper – FormIterator: a smart mans request data extractor
<form name="test" id="form-id">
<label for="name">Name</label>
<input name="name" id="name" type="text">
<label for="pass">Password</label>
<input name="pass" id="pass" type="text">
</form>
<script>
var it = new FormData( document.getElementById('form-id') ).entries();
var current = {};
while ( ! current.done ) {
current = it.next();
console.info( current )
}
</script>
or…
<script>
// props @soulmerge
var it = new FormData( document.getElementById('form-id') ).entries();
for ( var current = it.next(); ! current.done; current = it.next() ) {
console.info( current.value );
}
</script>
// NodeIterator that fetches all text node and filters out nodes with no content
var nodeIterator = document.createNodeIterator(
document.body,
NodeFilter.SHOW_TEXT,
{
acceptNode : function( node ) {
if ( ! /^\s*$/.test( node.data ) ) {
return NodeFilter.FILTER_ACCEPT;
}
}
}
);
// Loop Nodes, Print results
while ( ( node = nodeIterator.nextNode() ) ) {
console.log( node.data );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment