Friday 10 July 2009

jQuery - Remove nodes based on value and attribute value

In this post we will go through the methods used to remove nodes from your XML Document/Object. To do this, we will be making use of the jQuery remove() function, along with some additional selectors.

Deleting nodes based on an attribute value is actually on of the easiest bits of code, due to the powerful selector engine in jQuery. You merely need to know the basic conditions for your search, and that's about it.

XML Example:




Philip Stone
28


Peter Jackson
32



Now let's say you want to completely remove the person node which has an ID of 2. To do that, you simply need to use:

$(xml).find("person[id='2']").remove();


Now the only thing you need to be careful with is that this will globally remove all nodes which match this criteria, so if you need to be a bit more specific, please do so, either with a more defined selector string, or some conditional statements. Speaking of conditional statements, you need to make basic use of them to remove a node based on it's value (rather than it's attributes value). So if you wanted to remove the 'name' node with the value of 'Peter Jackson', you would need:

$(xml).find("name").each(function() {
if ($(this).text() == "Peter Jackson")
$(this).remove();
});


The above code basically does a search for all name nodes, iterates through them all, checks if their value is matches our criteria, and then removes them. Obviously, as mentioned with the attribute removal, if you need additional conditional statements to be more precise in what you remove, please extend the code.

No comments: