Reputation: 551
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
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.
Upvotes: 8
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
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