Reputation: 905
$(document).ready(function(){
var x = '<div><span></span><div id="container"><span>one</span><span class="target"></span></div></div>';
console.log($(x).find('#container').get(0));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I am able to get the container block but how to remove the .target span
?
Upvotes: 0
Views: 109
Reputation: 1423
Are you looking to remove the entire element if the class
matches .target
?
Try this:
$(document).ready(function(){
var x = $('<div><span></span><div id="container"><span>one</span><span class="target"></span></div></div>');
x.find('.target').get(0).remove();
console.log(x.html());
});
Here's a fiddle.
Edit
As x.html()
strips off the root element (i.e. the <div></div>
), here is the solution if you would like to get the full HTML string.
$(document).ready(function(){
var x = $('<div><span></span><div id="container"><span>one</span><span class="target"></span></div></div>');
x.find('.target').get(0).remove();
x = x.wrap('<div>').parent().html();
console.log(x);
});
Updated fiddle.
Edit 2
In the case where there are more than one .target
, say for example the following string:
<div><span></span><div id="container"><span>one</span><span class="target"></span><span class="target"></span><i class="target"></i></div></div>
You can consider removing get(0)
.
$(document).ready(function(){
var x = $('<div><span></span><div id="container"><span>one</span><span class="target"></span><span class="target"></span><i class="target"></i></div></div>');
x.find('.target').remove();
x = x.wrap('<div>').parent().html();
console.log(x);
});
Updated the fiddle again.
Upvotes: 3
Reputation: 375
This should work:
$(document).ready(function() {
var x = '<div><span></span><div id="container"><span>one</span><span id="target">ssss</span></div></div>';
var y = $(x).find("#target").remove().text();
//$(x).find(".target").remove();
$('#new').append( "<p>Test</p>" + y);
});
Upvotes: 0
Reputation: 32354
Try:
var x = '<div><span></span><div id="container"><span>one</span><span class="target"></span></div></div>';
var elem = $(x).find("#container").parent();
elem.find('.target').remove();
var div = $('<div>').append(elem).html();
console.log(div);
Upvotes: 0
Reputation: 2415
See below.
FYI -- there is no span inside element with class of target... so doing '.target span' kinda makes no sense
var x = '<div><span></span><div id="container"><span>one</span><span class="target"></span></div></div>';
var elem = $(x).find("#container").parent();
elem.find('.target').remove();
Upvotes: 0