考虑这个我的价值:
var value = "<br><br><div class="test">-- Thanks, <br><div><br></div></div>";
我想删除测试类div标签,即<div class="test1">
并与结束标记</div>
相关。
期待结果将是:
"<br><br>-- Thanks, <br><div><br></div>"
我正在尝试使用正则表达式:
value = value.replace(/(<div class="test">|<\/div>)/g, '');
但它删除了相邻的div标签:
<br><br><div class="test">-- Thanks, <br><div><br>
与结束标签不完全相同。
怎么做?
答案 0 :(得分:1)
这里最好的选择是使用浏览器内置的HTML解析器。例如:
var div, divToRemove, node, sibling;
div = document.createElement('div');
div.innerHTML = value;
divToRemove = div.querySelector('.test');
for (node = divToRemove.firstChild, sibling = node.nextSibling;
node;
node = sibling, sibling = node && node.nextSibling) {
divToRemove.parentNode.insertBefore(node, divToRemove);
}
divToRemove.parentNode.removeChild(divToRemove);
value = div.innerHTML;
直播示例:
var value = '<br><br><div class="test">-- Thanks, <br><div><br></div></div>';
snippet.log("Before: " + value);
var div, divToRemove, node, sibling;
div = document.createElement('div');
div.innerHTML = value;
divToRemove = div.querySelector('.test');
for (node = divToRemove.firstChild, sibling = node.nextSibling; node; node = sibling, sibling = node && node.nextSibling) {
divToRemove.parentNode.insertBefore(node, divToRemove);
}
divToRemove.parentNode.removeChild(divToRemove);
value = div.innerHTML;
snippet.log("After: " + value);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
答案 1 :(得分:0)
您需要先将父div的html保存在变量
中var html = document.getElementByClassName('test1').innerHtml;
然后删除div:
document.getElementByClassName('test1').remove();
然后将html附加到div的父级
var bodyHtml = document.getElementByTagName('body');
bodyHtml = bodyHtml + html;
答案 2 :(得分:0)
使用DOM来正确
var html = '<br><br><div class="test">-- Thanks, <br><div><br></div></div>';
var frag = document.createElement('div');
frag.innerHTML = html;
var tgt = frag.querySelector('.test');
var par = tgt.parentNode;
while(tgt.firstChild) {
par.insertBefore(tgt.firstChild, tgt);
};
tgt.remove();
console.log(frag.innerHTML);