Skip to content

Instantly share code, notes, and snippets.

@ahmedash95
Last active December 4, 2016 23:41
Show Gist options
  • Save ahmedash95/d9fb4513e081309eab8e5b5a0db7284c to your computer and use it in GitHub Desktop.
Save ahmedash95/d9fb4513e081309eab8e5b5a0db7284c to your computer and use it in GitHub Desktop.
nodes html changer
window.replaceTextIndex = [];
function replaceText(element, text, newText) {
var regextPattern = new RegExp(text, "g");
if (typeof element === 'string' || element instanceof String)
element = document.querySelector(element);
element.childNodes.forEach(function(node, index) {
if (node.tagName == "P" || node.tagName == "DIV" || node.tagName == undefined || node.tagName == "SPAN") {
if (node.tagName == undefined && node.nodeValue != "") { // it's text
if(node.nodeType != Node.COMMENT_NODE && node.nodeValue.trim().length > 0)
{
var newNodeElement = document.createElement("span");
newNodeElement.innerHTML = node.nodeValue.replace(regextPattern, function(match,i){
if(window.replaceTextIndex[text] === undefined)
window.replaceTextIndex[text] = 0;
if(window.replaceTextIndex[text] > 2)
return text;
window.replaceTextIndex[text]++;
return newText;
});
node.parentNode.replaceChild(newNodeElement,node);
}
} else {
replaceText(element.childNodes[index],text,newText);
}
}
})
}
// example
// <div id="content">Hi gist , <p style="color:red">this is test for gist</p> <div><p><span>bye gist</span></p></div>
// in script.js
// replaceText('#content','gist','Ahmed Ashraf')
// result
// <div id="content"><p>Hi Ahmed Ashraf , </p><p style="color:red">this is test for Ahmed Ashraf</p><p> </p><div><p><span>bye Ahmed Ashraf</span></p></div><p></p></div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment