I’ve got the following code:
var $elements = $("body").find("*");
for (var i = 0, len = $elements.length; i < len; i++) {
var $e = $elements.eq(i),
cssFloat = $e.css("float"),
cssDisplay = $e.css("display");
if (cssDisplay !== "none" &&
(cssFloat === "left" || cssFloat === "right")) {
$e.css("display", "inline");
}
};
For performance reasons, I would like to replace the for loop and if statement with a jQuery selector that filters down all the elements to only the ones that need to apply the display: inline;.
I was thinking something along the lines of the following pseudo code:
$("body")
.find("*")
.not(selector for elements whose css display style is not "none")
.contains(selector for elements whose css float style is "left" or "right")
.css("display", "inline");
For whatever reason, my brain is failing me. Is this possible?
You could use the
$.filter()method to get what you want:This would result in the floated elements being turned into inline elements.
Demo: http://jsbin.com/utape3/edit
While the jQuery documentation states there will be performance issues using
:visible, it is more efficient than using*orbody *.Performance Comparison: http://jsperf.com/splat-vs-pseudo
I’m not sure of a faster method of doing this with JavaScript. You’ll notice in the performance test that I used everything including a custom selector:
I was really only partly interested in the results of that method, not being entirely familiar with how the internals handle this type of selector.
Raw JavaScript – Much Faster
I’ve added to the performance testing the following:
This test assumes:
This was thrown together, but ridiculously fast compared to the previous jQuery methods.