Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove XML node with jQuery .each and $(this)

Tags:

jquery

xml

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

like image 614
Shane Avatar asked Nov 09 '11 13:11

Shane


1 Answers

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.

like image 72
Frédéric Hamidi Avatar answered Oct 21 '22 04:10

Frédéric Hamidi