简体   繁体   English

从html字符串中删除div及其内容

[英]Remove div and its content from html string

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>

I want to remove div2 from the string and everything inside that div 我想从字符串和div中的所有内容中删除div2

So i got a string like this 所以我得到了这样的字符串

<div id="div1"></div>
<div id="div5"></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>". 我想像使用正则表达式来找到id为“div2”的第一个div或div的id是什么,并计算括号,直到它变为“</ div>”。 The problem is that the "div3" also got a "< /div>" at the end. 问题是“div3”最后还有一个“</ div>”。

The content of the div i want to remove may contain more or less div's then this too. 我要删除的div的内容可能包含更多或更少的div,然后这也是。

Any ideas on how to code this? 有关如何编码的任何想法?

Update: 更新:

                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!: I have made a jsFiddle to make my problem visual.. http://jsfiddle.net/WGXHS/ Update2!:我已经制作了一个jsFiddle让我的问题可视化.. http://jsfiddle.net/WGXHS/

Just put the string into jQuery and use find and then remove. 只需将字符串放入jQuery并使用find然后删除即可。

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

jQuery .remove()会做的

$("#div2").remove();

If you have access to jQuery and your HTML is part of the DOM you can use $.remove() 如果你有权访问jQuery并且你的HTML是DOM的一部分你可以使用$ .remove()

EG. 例如。 $('#div2').remove();

If it's not part of the DOM, and you have it in a string, you can do something like: 如果它不是DOM的一部分,并且你有一个字符串,你可以这样做:

$('#div2', $(myHTML)).remove();

The regex option would work if you control generating the string so you can ensure things like order of the attributes and indentation. 如果您控制生成字符串,则可以使用正则表达式选项,这样您就可以确保属性和缩进的顺序。 If not your best bet is to use an HTML parser. 如果不是你最好的选择是使用HTML解析器。 If you are working inside of a browser jQuery is a good option. 如果你在浏览器中工作,jQuery是一个不错的选择。 If you are working server-side you'll need to find a parser for the language you chose. 如果您在服务器端工作,则需要找到所选语言的解析器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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