JQuery - more efficiently 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");
...
..
.

more efficient to do this or something like this:

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

ideas?

+1
source share
3 answers

As for the fastest selectors, it's best 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(){});
+1
source

No matter how you select them, you still need to do each()it if your sample code is similar to your real code. This is because you pass unique data for each function call.

But you should add tagNameto the selector, at least.

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

tagName jQuery , input.

+1

^= Operator characters begin with:

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

All Articles