Created
May 13, 2016 08:28
-
-
Save matesnippets/03aa59e1172eca91382adf7510677996 to your computer and use it in GitHub Desktop.
Replaces placeholder values, or text, or attributes in the DOM.
This file contains 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
'use strict'; | |
define(function () { | |
var substitute = {}; | |
substitute.placeholders = function (target, replaceObject) { | |
_replaceStuff(target, replaceObject, 'placeholders'); | |
}; | |
substitute.attribute = function (target, replaceObject) { | |
_replaceStuff(target, replaceObject, 'attribute'); | |
}; | |
substitute.html = function (target, newValue) { | |
var targetElements = document.querySelectorAll(target || '.stubber'); | |
for (var i = 0; i < targetElements.length; i++) { | |
var el = targetElements[i]; | |
el.innerHTML = newValue; | |
} | |
}; | |
function _replaceStuff(target, replaceObject, typeOfReplace) { | |
var targetElements = document.querySelectorAll(target || '.stubber'), | |
stubs = Object.keys(replaceObject); | |
if (!targetElements.length || !stubs.length || !typeOfReplace) { | |
return; | |
} | |
for (var i = 0; i < targetElements.length; i++) { | |
var el = targetElements[i]; | |
stubs.forEach(function (stub) { | |
if (typeOfReplace === 'placeholders') { | |
var stubRegex = new RegExp(stub, 'g'); | |
el.innerHTML = el.innerHTML.replace(stubRegex, replaceObject[stub]); | |
} | |
else { | |
el.setAttribute(stub, replaceObject[stub]); | |
} | |
}); | |
} | |
}; | |
return substitute; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment