Rashmi
Rashmi

Reputation: 551

How to remove a div with particular class or id from a string using jquery?

i have a string

var c = '<div class="main">
             <div class="child1">text 1</div>
             <div class="child1">text 2</div>
             <div class="child2">text 2</div>
         </div>';

Now i want to remove child2 from this string only ..

I tried this

var $c = $(c).not('child2');

but its not working Any body have solution regarding this. Please let me know

Thanks

Upvotes: 2

Views: 1693

Answers (3)

PSL
PSL

Reputation: 123739

Try this:

var c ='<div class="main"><div class="child1"> text 1</div><div class="child1"> text 2</div><div class="child2"> text 2</div></div>';
var $c = $(c); //Get the JQ object to a var
$c.find('.child2').remove(); //Remove it from there
c = $c.html(); //Get back the html

Unfortunately

$(c).find('.child2').remove() wont remove it at source as it is not in DOM and is just a string. So you need to get the object to a temp variable and then remove it from that and get back the html string out of it.

Demo

Upvotes: 8

br araujo
br araujo

Reputation: 1872

Without jquery:

var tempDiv = document.createElement('div');
var c ='<div class="main"><div class="child1"> text 1</div><div class="child1"> text 2</div><div class="child2"> text 2</div></div>';
var removableChild = tempDiv.getElementsByClassName("child2")[0];
removableChild.parentElement.removeChild(removableChild);
var c = tempDiv.innerHTML;

Upvotes: 0

Rohan Kumar
Rohan Kumar

Reputation: 40639

Use $.parseHTML first then remove

var c ='<div class="main"><div class="child1"> text 1</div><div class="child1"> text 2</div><div class="child2"> text 2</div></div>';
c=$.parseHTML(c);
$(c).find('.child2').remove();
console.log($(c));

Fiddle http://jsfiddle.net/78m4J/

Upvotes: 0

Related Questions