I'm trying to replace the <span>
tags with the tags <a>
My initial html is:
<p>
<span class="mention" data-label="59c01a091ebfff41906d6faa">Cesar Romero</span>
<span class="mention" data-label="59b81da0c9c18e778824447a">Gustavo Medina</span>
<span class="mention" data-label="59bcd70b2d488f3c64efbceb">Ramses Coraspe</span>
<span class="mention" data-label="59bfd252bfb7a7024070c2f1">carlos valdez</span>
</p>
After function executing the output is:
<p>
<a class="mention" href="/professional/59c01a091ebfff41906d6faa">Cesar Romero</a>
<span class="mention" data-label="59b81da0c9c18e778824447a">Gustavo Medina</span>
<a class="mention" href="/professional/59bcd70b2d488f3c64efbceb">Ramses Coraspe</a>
<span class="mention" data-label="59bfd252bfb7a7024070c2f1">carlos valdez</span>
</p>
For some strange reason the replaceChild does does not the replacement in all iterations.
The code I am using is:
function ProcessPost(htmlstring){
var parser = new DOMParser();
var doc = parser.parseFromString(htmlstring, "text/html");
var elements = doc.getElementsByTagName ("p");
if (elements.length>0){
for(var i =0; i < elements.length; i++){
var spans= elements[i].getElementsByTagName ("span");
for(var j =0; j<spans.length; j++){
var aTag = document.createElement("a");
aTag.setAttribute("class", spans[j].getAttribute("class"));
aTag.setAttribute("href", createUrl(spans[j]));
var aTag_content = document.createTextNode(spans[j].innerText);
aTag.appendChild(aTag_content);
var parentSpan = spans[j].parentNode;
parentSpan.replaceChild(aTag, spans[j]);
}
console.log(elements[i])
}
}
}
Has anyone had experience in using replaceChild? Could you help me find what I'm doing wrong?
` you should input only querySelectorAll('p'). The main advantage of using querySelector is that it doesn't return a live list (it returns a static list), while getElements... does, and this is not good for iteration
– flen Jan 12 '18 at 02:20