In any event, using the element's type together with a class selector
will improve performance (otherwise every single element in the
current context is checked for that class):

$('div.toto').hide();

With a single element (or very few) using an id will probably be
faster, but with 50+ elements, it might be faster to optimize the
query instead and use a class plus context...:

$('div.toto', '#container').hide();

or even, depending on the markup:

$('> div.toto', '#container').hide();

(#container would be a div that contains all divs that belong to the
class "toto").

But maybe that still wouldn't beat getElementById. Instead of us
speculating here, you should simply test performance with FireBug
yourself and see what works best:

console.time('first');
$("div[id^='toto']").hide();
console.timeEnd('first');

console.time('second');
$('div.toto').hide();
console.timeEnd('second');

and so on...

Depending on how you can adapt markup another option to improve
performance would be to skip classes at all and just use context:

<div id="toto">
    <div></div>
    <div></div>
    ...
</div>

$('#toto div').hide();

Again, you'd need to verify what's the fastest.


--Klaus



On 5 Jan., 16:50, Christof Donat <cdo...@gmx.de> wrote:
> Hi,
>
> > And try something like:
>
> > var toto = [];
> > $('.toto').each(function(){
> >     var elem = $(this);
> >     toto[elem.attr('ref')] = elem;
> > }
>
> > Then, to hide the "toto" div with ref="1" or ref="2", just call:
>
> > toto[1].hide(); toto[2].hide();
>
> Why not use this:
>
> var toto = $('.toto');
> toto[1].hide(); toto[2].hide();
>
> That should be the same.
>
> Appart from that I think, that Jean Babtiste wanted to hide all elements at
> the same time. I'd expect his first ( $('.toto').hide() ) version to be
> usually faster, but I'm not shure about that.
>
> Christof

Reply via email to