Skip to content

Instantly share code, notes, and snippets.

@mysiar
Created November 14, 2018 17:53
Show Gist options
  • Save mysiar/86c5ceb53c86c22a26872ec601f13a09 to your computer and use it in GitHub Desktop.
Save mysiar/86c5ceb53c86c22a26872ec601f13a09 to your computer and use it in GitHub Desktop.
replaceElementNodeValue
/*
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