[英]Remove parent <div> tag end of </div> closing tag using javascript
Consider this my value: 考虑一下我的价值:
var value = "<br><br><div class="test">-- Thanks, <br><div><br></div></div>";
I want to remove test class div tag ie <div class="test1">
and related to closing tag </div>
. 我想删除测试类div标签,即
<div class="test1">
并与结束标签</div>
。
Expecting results will be: 预期结果将是:
"<br><br>-- Thanks, <br><div><br></div>"
I am trying with regular expression: 我正在尝试使用正则表达式:
value = value.replace(/(<div class="test">|<\/div>)/g, '');
but it's removing adjacent div tag: 但是它正在删除相邻的div标签:
<br><br><div class="test">-- Thanks, <br><div><br>
not the exactly with the closing tag. 不完全与结束标记。
How to do this? 这个怎么做?
Your best bet here is to use the HTML parser built into the browser. 最好的选择是使用浏览器中内置的HTML解析器。 For instance:
例如:
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;
Live Example: 现场示例:
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>
You need to first save parent div's html in a variable 您需要先将父div的html保存到变量中
var html = document.getElementByClassName('test1').innerHtml;
Then remove the div: 然后删除div:
document.getElementByClassName('test1').remove();
Then append the html to the parent of the div 然后将html附加到div的父级
var bodyHtml = document.getElementByTagName('body');
bodyHtml = bodyHtml + html;
Use the DOM to get it right 使用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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.