简体   繁体   中英

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> .

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:

<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. 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

var html = document.getElementByClassName('test1').innerHtml;

Then remove the div:

document.getElementByClassName('test1').remove();

Then append the html to the parent of the div

var bodyHtml = document.getElementByTagName('body');

bodyHtml = bodyHtml + html;

Use the DOM to get it right

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM