kralco626
kralco626

Reputation: 8624

Jquery - more efficient to use multiple selectors, or each

I have something like this

<input class = "Class1"/>
<input class = "Class2"/>
<input class = "Class3"/>
<input class = "Class4"/>
...
..
.

$(".Class1").someFunction("data1");
$(".Class2").someFunction("data2");
$(".Class3").someFunction("data3");
$(".Class4").someFunction("data4");
...
..
.

is it more efficient to do that or something like this:

<input something="data1"/>
<input something="data2"/>
<input something="data3"/>
<input something="data4"/>
...
..
.
$("[something]").each($(this).someFunction($(this).attr("something")));

ideas?

Upvotes: 1

Views: 464

Answers (3)

hungryMind
hungryMind

Reputation: 6999

^= operator matches starts with too:

$("input[class^=Class]").each($(this).someFunction($(this).attr("something")));

Upvotes: 0

user113716
user113716

Reputation: 322492

Irrespective of how you select them, you'll need to do an each() anyway if your code example is anything like you're real code.This is because you're passing unique data to each function call.

But you should add a tagName to the selector at the very least.

$("input[something]").each(function() {
    $(this).someFunction($(this).attr("something"));
});

Without the tagName, jQuery will need to look at every element on the page, instead of just input elements.

Upvotes: 1

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

As far as fastest selectors go it would be better to do:

<div id="container">
    <input data-something="1" />
    <input data-something="2" />
    <input data-something="3" />
    <input data-something="4" />
</div>

Then you can do:

$('#container input').each(function(){});

Upvotes: 1

Related Questions