Created
November 14, 2018 17:53
-
-
Save mysiar/86c5ceb53c86c22a26872ec601f13a09 to your computer and use it in GitHub Desktop.
replaceElementNodeValue
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
/* | |
replaceElementNodeValue | |
this function works if only ONE element with nodeClass is found | |
element - DOM element with nested different elements | |
nodeClass - class of node that value we want to replace | |
nodeNewValue - selfexplaining | |
*/ | |
replaceElementNodeValue = (element, nodeClass, nodeNewValue) => { | |
const elementTagName = element.tagName; | |
let el = element.cloneNode(true); | |
if (el.getElementsByClassName(nodeClass).length !== 1) throw new Error('Something wrong. None or more than one element found'); | |
let node = Array.from(el.getElementsByClassName(nodeClass))[0]; | |
node.innerHTML = nodeNewValue; | |
do { | |
const parentNode = node.parentElement; | |
parentNode.replaceChild(node, node); | |
if (parentNode.tagName === elementTagName) { | |
el = parentNode.cloneNode(true); | |
break; | |
} | |
node = parentNode; | |
} while (1); | |
return el; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment