Removing <span> tag while leaving content intact, with just javascript

浪子不回头ぞ 提交于 2019-12-11 11:22:31

问题


I'm doing some in page highlighting, and found the most popular example when using text selection and adding spans is by switching to designMode and running execCommand

How can I highlight the text of the DOM Range object?

There's no follow up though on how to remove the span tags once created. I saw some examples using jquery and the replaceWith, but none with straight javascript.


回答1:


You should be able to do something like:

// Where span is a reference to the span to be replaced
var text = span.textContent || span.innerText;
var node = document.createTextNode(text);
span.parentNode.replaceChild(node, span);



回答2:


Just create a new text node with the contents (innerHTML) of the <span>. Replace the <span> node with replaceChild on its parent:

spanTag.parentNode.replaceChild(document.createTextNode(spanTag.innerHTML), spanTag)



来源:https://stackoverflow.com/questions/7947763/removing-span-tag-while-leaving-content-intact-with-just-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!