Koiski
Koiski

Reputation: 568

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

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>". The problem is that the "div3" also got a "< /div>" at the end.

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?

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/

Upvotes: 3

Views: 17454

Answers (4)

Patrick Evans
Patrick Evans

Reputation: 42736

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

Upvotes: 15

Jude Duran
Jude Duran

Reputation: 2205

jQuery .remove() will do

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

Upvotes: 1

Joe
Joe

Reputation: 28316

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. If you are working inside of a browser jQuery is a good option. If you are working server-side you'll need to find a parser for the language you chose.

Upvotes: 0

itsmejodie
itsmejodie

Reputation: 4228

If you have access to jQuery and your HTML is part of the DOM you can use $.remove()

EG. $('#div2').remove();

If it's not part of the DOM, and you have it in a string, you can do something like:

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

Upvotes: 2

Related Questions