get selected options, jQuery vs pure JS

JavaScript performance comparison

Test case created by Baptiste Fontaine

Info

The goal is to get all selected options of a <select> element. Here, I use the "selected" attribute, but in fact when the user selects an option, it doesn't add it the "selected" attribute, so I won't use it in the code.

Preparation code

<script src="//code.jquery.com/jquery-git.js"></script>
<select id="selectid" multiple>
  <option value="val1">Option1</option>
  <option value="val2" selected>Option2</option>
  <option value="val3">Option3</option>
  <option value="val4" selected>Option4</option>
  <option value="val5" selected>Option5/option>
  <option value="val6">Option6</option>
  <option value="val7">Option7</option>
  <option value="val8">Option8</option>
  <option value="val9" selected>Option9</option>
  <option value="val10">Option10</option>
  <option value="val11">Option11</option>
  <option value="val12" selected>Option12</option>
  <option value="val13">Option13</option>
  <option value="val14">Option14</option>
  <option value="val15" selected>Option15</option>
  <option value="val16" selected>Option16</option>
  <option value="val17">Option17</option>
</select>

Preparation code output

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
jQuery
$("#selectid").on("change", function() {
      var selected = $("option:selected", this).map(function() {
        return $(this).text();
      }).toArray().join(", ");
     
      console.log(selected);
});
pending…
pure JS
document.getElementById('selectid').onchange = function(e,selected) {
    selected = [].filter.call(e.target, function(o) {return o.selected;})
        .map(function(o){return o.innerText;})
        .join(', ');

    console.log(selected);
}
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 comments

Add a comment