从html字符串中删除div及其内容 [英] Remove div and its content from html string

查看:156
本文介绍了从html字符串中删除div及其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的字符串:

Lets say i have a string like this:

<div id="div1"></div>
<div class="aClass" id="div2">  
   <div id="div3" class="anotherClass"></div>
   <div id="div4" />
</div>
<div id="div5"></div>

我想从字符串中删除div2以及div中的所有内容

I want to remove div2 from the string and everything inside that div

所以我得到一个这样的字符串

So i got a string like this

<div id="div1"></div>
<div id="div5"></div>

我在想像使用正则表达式找到id为div2的第一个div或者其他什么div的id是和count括号,直到它变为< / div>。问题是div3最后还得到了一个< / div>。

I thinking something like using regex to find the first div with the id of "div2" or whatever the id of the div is and count brackets untill it gets to "< /div>". The problem is that the "div3" also got a "< /div>" at the end.

我要删除的div的内容可能包含更多或更少的div。然后这个。

The content of the div i want to remove may contain more or less div's then this too.

任何关于如何编码的想法?

Any ideas on how to code this?

更新:

                var htmlText = editor3.getValue();
            var jHtmlObject = jQuery(htmlText);
            jHtmlObject.find("#div2").remove();
            var newHtml = jHtmlObject.html();
            console.log(newHtml);

为什么这不会在控制台中返回任何内容?

Why doesn't this return anything in the console?

Update2!:
我已经制作了一个jsFiddle来解决我的问题。
http://jsfiddle.net/WGXHS/

Update2!: I have made a jsFiddle to make my problem visual.. http://jsfiddle.net/WGXHS/

推荐答案

只需将字符串放入jQuery并使用find然后删除。

Just put the string into jQuery and use find and then remove.

var htmlString = '<div id="div1"></div>\
<div class="aClass" id="div2">\ 
   <div id="div3" class="anotherClass"></div>\
   <div id="div4" />\
</div>\
<div id="div5"></div>';

var jHtmlObject = jQuery(htmlString);
var editor = jQuery("<p>").append(jHtmlObject);
editor.find("#div2").remove();
var newHtml = editor.html();

这篇关于从html字符串中删除div及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆