I have been using this method for a while now having initially not put any research into it.
$("div#panel-frame div.panel.txt select.fontsize").live('change', function ()
{
var parent = $(this).parents('div.panel.txt');
});
So as you can see from the code above, I’m trying to get access to a parent of select.fontsize. The parent I’m trying to get to is div.panel.txt – as you can see, I’m accessing it by saying $(this).parents(‘div.panel.txt’)
This method works but I’m wondering if there is a better way of doing it? Ideally I want it to be as fast and efficient as possible.
What you have inside your change function should be efficient enough, though if you know that the element you want is the direct parent, you should use .parent() instead of .parents(). As other people have said, if you don’t know whether it’s the direct parent, use .closest() instead of .parents().
In theory, you can use
this.parentNodeto get the parent – regardless of its node or class names – with native DOM traversal (that is, without using jQuery), and that might be a bit quicker. However, you would need to write your own checks to make sure the node and class names match, so any gains you make would probably be lost again. This is basically what jQuery is doing under the hood anyway, and jQuery is very heavily optimised already.Your
.liveselector$("div#panel-frame div.panel.txt select.fontsize")is probably a bigger worry in terms of speed..live()works by assigning an event to the body element, and then watching the targets of events as they bubble up. So, when any ‘change’ event hits the body, jQuery needs to check if it originated at something matching'div#panel-frame div.panel.txt select.fontsize', which is a very slow operation, especially in older browsers.It would probably be quicker to just bind
.live()to $(‘select.fontsize’), and then check if the select element is the kind you want within the event handler itself. That way, jQuery can use the browser’s native ‘getElementsByTagName’, which is a fast operation. Better yet, give yourselect.fontsizeelements a more specific class name, so you know in advance that they’re the ones you want.