Created
September 2, 2014 03:58
-
-
Save yyfrankyy/64c0fbe1a6eebc1ffae8 to your computer and use it in GitHub Desktop.
Extendable Linkify Implementation
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
function linkify(el, transforms) { | |
var node, nodes = [], | |
count = 0, loop = 0, match = 0; | |
var walker = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, { | |
acceptNode: function(node) { | |
if (!(node.parentNode | |
&& node.parentNode.nodeName.toUpperCase() == 'A' | |
|| node.parentNode.nodeName.toUpperCase() == 'STYLE')) { | |
return NodeFilter.FILTER_ACCEPT; | |
} | |
} | |
}, false); | |
while (node = walker.nextNode()) nodes.push(node); | |
while (node = nodes.shift()) { | |
count++; | |
(function transform(node, i) { | |
i = i || 0; | |
var originalText = node.textContent; | |
if (!transforms[i] || originalText.trim().length == 0) return; | |
loop++; | |
var newText = transforms[i](originalText); | |
if (originalText != newText) { | |
match++; | |
var newNode = document.createElement('span'); | |
newNode.innerHTML = newText; | |
node.parentNode.insertBefore(newNode, node); | |
node.parentNode.removeChild(node); | |
if (newNode.prevSibling) nodes.push(newNode.prevSibling); | |
if (newNode.nextSibling) nodes.push(newNode.nextSibling); | |
} else { | |
transform(node, i+1) | |
} | |
})(node); | |
} | |
return [count, loop, match] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment