Last active
December 5, 2019 10:35
-
-
Save kotarok/8a956fa0d23927221849 to your computer and use it in GitHub Desktop.
Walk DOM tree to extract textNode and apply given mutator function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extract textNodes from the tree of given root element. And apply given | |
* function to each textNodes. | |
* @param {HTMLElement} rootEl Target DOM sub tree root. | |
* @param {Function} processor Processor function | |
* @param {Object} option Config to override | |
*/ | |
var processTextNodes = function(rootEl, processor, option) { | |
var conf = { | |
dummyElementName: 'dummy', | |
ignoreElem: ['CODE', 'KBD'] | |
}; | |
if (option) { | |
Object.keys(option).forEach(function(key) { | |
conf[key] = option[key]; | |
}); | |
} | |
var dummyElementName = conf.dummyElementName; | |
var dummyElementRE = new RegExp('<\\/?' + dummyElementName + '>', 'g'); | |
var process_ = function(rootEl) { | |
[].forEach.call(rootEl.childNodes, function(childNode) { | |
if ( | |
childNode.nodeType === Node.TEXT_NODE && | |
conf.ignoreElem.indexOf(childNode.nodeName) > -1 | |
) { | |
var dummy = document.createElement(dummyElementName); | |
dummy.innerHTML = processor(childNode.data); | |
childNode.parentNode.replaceChild(dummy, childNode); | |
} else if (childNode.nodeType === Node.ELEMENT_NODE) { | |
process_(childNode); | |
} | |
}); | |
}; | |
process_(rootEl); | |
[].forEach.call(rootEl.querySelectorAll(dummyElementName), function(dummy) { | |
dummy.outerHTML = dummy.outerHTML.replace(dummyElementRE, ''); | |
}); | |
}; | |
export default processTextNodes; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment