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?
I would pre-query the elements, like so:
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/