I created a small jsfiddle: http://jsfiddle.net/duRXc/
<div data-role="wrapper">
<span class="to-be-removed" data-role="to-be-removed">
text to be removed
</span>
</div>
<button id="remove1">Remove by jQuery object</button><br>
<button id="remove2">Remove by selector</button><br>
<button id="remove3">Remove by selector(class)</button>
var $wrapper = $('[data-role="wrapper"]');
$('#remove1').on('click', function () {
$wrapper.find('[data-role="to-be-removed"]').remove();
});
// this should work: http://api.jquery.com/remove/
$('#remove2').on('click', function () {
$wrapper.remove('[data-role="to-be-removed"]');
});
// this should work: http://api.jquery.com/remove/
$('#remove3').on('click', function () {
$wrapper.remove('.to-be-removed');
});
The problem I'm having is that the .remove(selector) overload is not working. I thought it had something to do with my data-role selector, but the remove by class selector doesn't work as well.
Am I doing something wrong? Or is this a bug in jQuery or maybe the docs are wrong:
We can also include a selector as an optional parameter
http://api.jquery.com/remove/
.remove( [selector ] )Returns: jQuery. Description: Remove the set of matched elements from the DOM. A selector expression that filters the set of matched elements to be removed. Similar to .empty(), the .remove() method takes elements out of the DOM.
The remove () method removes the selected elements, including all text and child nodes. This method also removes data and events of the selected elements. Tip: To remove the elements without removing data and events, use the detach () method instead. Tip: To remove only the content from the selected elements, use the empty () method.
Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.
Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach() instead.
$wrapper.find('span').remove('[data-role="to-be-removed"]')
is the same as
$wrapper.find('span').filter('[data-role="to-be-removed"]').remove()
var $wrapper = $('[data-role="wrapper"]');
$('#remove1').on('click', function () {
$wrapper.find('[data-role="to-be-removed"]').remove();
});
// this should work: http://api.jquery.com/remove/
$('#remove2').on('click', function () {
$wrapper.find('[data-role="to-be-removed"]').remove('[data-role="to-be-removed"]');
});
// this should work: http://api.jquery.com/remove/
$('#remove3').on('click', function () {
$wrapper.find('[data-role="to-be-removed"]').remove('.to-be-removed');
});
http://jsfiddle.net/duRXc/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With