Reputation: 31709
I expect not to get "hello" after pressing the button on the code below. So.. how can I remove the span
element from foo
variable and append it to body
?
$('button').on('click', function() {
var foo = '<div><span>hello</span></div>';
$(foo).find('span').remove();
$('body').append($(foo));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click here</button>
Upvotes: 0
Views: 28
Reputation: 15501
Wrap '<div><span>hello</span>world</div>'
inside $()
so its a jQuery object. That is all you need!
I have added string world
in the <div>
so you know that <span>
was removed after clicking the button.
$('button').on('click', function() {
var foo = $('<div><span>hello</span>world</div>');
$(foo).find('span').remove();
$('body').append($(foo));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click here</button>
Upvotes: 0
Reputation: 3171
You're trying to remove an element from text. Convert it to a jQuery object by wrapping the string '<div><span>hello</span></div>'
with $()
like so:
$('button').on('click', function() {
var foo = $('<div>-<span>hello</span>-</div>');
$(foo).find('span').remove();
$('body').append($(foo));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>click here</button>
I've added hyphens so that you can see that the <span>
is being removed, but elements are still being added.
Upvotes: 1