views:

100

answers:

4

I am using the following code to remove an element from the DOM tree:

 function onItemDeleted(name) {

           $("#" + name).remove();                       

       }

Would this be bad for performance since I am not indicating any parent for the element. The element is a TR contained in a TABLE element. The DOM search for this element will start at the top which might be BODY. So would it be something like this:

BODY => DIV => TABLE => TR (found)

If I find the parent of TR which is TABLE would the search be like this:

TABLE -> TR

I don't know if above will be true since I think search will always start at the root node.

+3  A: 

The difference in performance would likely be negligible.

Jonathan Sampson
+7  A: 

jQuery optimises for ID searches. So, $("#" + name) is effectively the same as $(document.getElementById(name)). From the source, line 120 (1.4):

// HANDLE: $("#id")
} else {
    elem = document.getElementById( match[2] );
J-P
I think it will make more sense to hold the parent when performing a lot of deletes in a short period of time. Since, then we don't have to search the DOM tree for the element again and again.
azamsharp
Incidentally it's not *quite* the same as `getElementById`, because a `.` or `:` character inside the ID (which are both valid) would break the selector version.
bobince
A: 

I guess that when you find elements by ID, the lookup time should be O(1) since there can be only one element with that ID.

Pablo Fernandez
A: 

Wouldn't removing a TR element be more complicated than just deleting it (e.g. taking care of containing TBODY's listst of child elements, firstChild etc...)?

Or does jQuery's remove() actually take care of such annoying details? (if so, I just found out a good enough reason to start learning jQuery :)

DVK