I am looping through some elements using jQuery's .each() and I want to delete a node when it meets certain requirements. I'm unsure of the syntax for this, I've tried several things:
$(this).remove();
$xml.remove(this);
$xml.removeNode(this);
...etc. Having some trouble finding a working example, could somebody point me in the right direction? I'm assuming it's simple, I just haven't been able to find the correct syntax. Got a non-working fiddle below.
http://jsfiddle.net/SHNpn/
Thanks
That's because the call to remove()
only removes the element from the DOM. It does not remove it from your $siblings
jQuery object.
If you call find()
again to rematch the siblings after removing the alex
node, you will get the expected results:
var $xml = $(xmlString);
var $siblings = $xml.find("sibling");
$siblings.each(function(){
var name = $(this).attr("name");
if (name == "alex")
$(this).remove();
});
// Here, the "alex" element is not in the DOM, but still part of $siblings.
$xml.find("sibling").each(function(){
var name = $(this).attr("name");
console.log(name);
});
// Since we're calling find() again, the code above will only print "bob".
You will find an updated fiddle here.
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