Question

Based on the answers to another mine question (this: How to make children auto fit parent's width only with CSS?), I'm thinking which is the best jQuery approach to solve the problem regarding performance.

Block 1: find all DOM elements when needed:

$("div.parent a").css("width", $("div.parent").width() / $("div.parent a").length - 2);

Block 2: find only DOM children, use each(), parent() and siblings():

$("div.parent a").each(function() {
    $(this).css("width", $(this).parent().width() / $(this).siblings().length - 2);
});

Block 3: find DOM parent first, use each() and find children based on context:

$("div.parent").each(function() {
    $("a", this).css("width", $(this).width() / $("a", this).length - 2);
});

Here is the Fiddle if someone wants to test: http://jsfiddle.net/ErickPetru/6nSEj/3/

So, which block is better? And why?

Was it helpful?

Solution

I would pre-query the elements, like so:

// find the elements you want to resize
var $links = $("div.parent a");

// resize them, and use the parent width
$links.width($links.parent().width() / $links.length - 2);

This way you're looking up the links, and looking up to the parent, only once. There's no looping, and there's no redundant queries.

Here's an example:

http://jsfiddle.net/xixionia/Gsek5/

OTHER TIPS

Using FireBug profiling:

  • block 1: 8.466 ms, 372 calls
  • block 2: 10.130 ms, 526 calls
  • block 3: 8.560 ms, 383 calls

also xixonia's answer was the fastest

  • xixonia: 8.205 ms, 369 calls

In order of speed:

  1. xixonia's
  2. block 1
  3. block 3

wouldn't even use block 2

I would say Block 1 would be best due to the fact that it does not require a loop,

You can also try this:

$("div.parent a").css({
    width: $(this).parent().width() / $(this).siblings().length - 2)
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top