Reputation: 5151
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.
Thanks
Upvotes: 5
Views: 8476
Reputation: 263137
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.
Upvotes: 5