azamsharp
azamsharp

Reputation: 20066

Removing HTML Element by Id

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.

Upvotes: 1

Views: 2128

Answers (3)

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

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.

Upvotes: 0

James
James

Reputation: 111900

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] );

Upvotes: 7

Sampson
Sampson

Reputation: 268344

The difference in performance would likely be negligible.

Upvotes: 3

Related Questions