我尝试将<span>
代码替换为代码<a>
我的初始HTML是:
<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>
执行输出后的函数是:
<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>
由于某些奇怪的原因,replaceChild不会在所有迭代中进行替换。
我使用的代码是:
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])
}
}
}
有没有人有使用replaceChild的经验?你能帮我找到我做错的事吗?
答案 0 :(得分:0)
使用 querySelectorAll
function sendPost(){
var parser = new DOMParser();
var doc = parser.parseFromString(vm.textEditor.doc, "text/html");
var elements = doc.querySelectorAll('p');
if (elements.length>0){
for(var i =0; i < elements.length; i++){
var spans= elements[i].querySelectorAll("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])
}
}
}