Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created November 18, 2009 20:08
Show Gist options
  • Save cowboy/238196 to your computer and use it in GitHub Desktop.
Save cowboy/238196 to your computer and use it in GitHub Desktop.
/*!
* JavaScript domReplace - v1.0pre - 11/18/2009
* http://benalman.com/projects/javascript-dom-replace/
*
* Copyright (c) 2009 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// jQuery not required:
//
// Usage:
//
// domReplace( document.body, /\bthe\b/ig, 'THE' );
// domReplace( document.body, /\b(the)\b/ig, function(a) { return '<strong>' + a + '<\/strong>'; }, true );
window.domReplace = (function(){
var elem;
return function( parent, search, replace, parse_html ) {
var children = parent.childNodes,
i = children.length,
child,
html;
while( --i >= 0 ) {
child = children[ i ];
if ( child.nodeType === 3 ) {
html = child.nodeValue.replace( search, replace );
if ( html !== child.nodeValue ) {
if ( parse_html ) {
elem = elem || document.createElement('b');
elem.innerHTML = html;
while ( elem_child = elem.firstChild ) {
parent.insertBefore( elem_child, child );
}
parent.removeChild( child );
} else {
child.nodeValue = html;
}
}
} else {
domReplace( child, search, replace, parse_html );
}
}
};
})();
// And jQuery support is here if you have jQuery:
//
// Usage:
//
// $('body').domReplace( /\bthe\b/ig, 'THE' );
// $('body').domReplace( /\b(the)\b/ig, function(a) { return '<strong>' + a + '<\/strong>'; }, true );
if ( window.jQuery ) {
jQuery.fn.domReplace = function( search, replace, parse_html ) {
return this.each(function(){
domReplace( this, search, replace, parse_html );
});
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment