javascript removeChild then replace this with new text using insertBefore
-
07-07-2021 - |
Question
I want to create a function in an external javascript file that I can reuse later (i.e. a modular function that is general enough to be used in whatever javascript it is needed in). I want to do this with pure JavaScript, not using jQuery or innerHTML.
I want this modular function to do the following: 1) remove an element of a child 2) replace this child with the new child value
For example say you had this code:
<p id="removeMe">This text needs to be removed</p>
<p id="nextPara">This is the paragraph that follows the replaced paragraph</p>
So I need to:
1) parentNode.removeChild(removeMe);
2) var replacementParagraph = document.createElement('p');
3) var replacementParagraphText =document.createTextNode("This is the replacementParagraph text);
4) replacementParagraph.appendChild(replacementParagraphText);
Now I just need to figure out how to write the modular function sort of like below:
function removeReplace (parameter, parameter) {
1) remove the child of the paragraph with the id of "removeMe"
2) use insertBefore(newText, nextPara) to replace the child that was removed in step 1
}
Thank you so much for your help, Jason
Solution
Oh, it's much easier because this function already exists natively: .replaceChild()
. Actually you've already got the algorithm, you just would need to write it in javascript:
function replaceElementByParagraph(id, text) {
var toremove = document.getElementById(id);
if (!toremove) // in case no element was found:
return false; // abort
var para = document.createElement('p');
para.appendChild(document.createTextNode(text));
return toremove.parentNode.replaceChild(para, toremove);
}