jquery append if not contains

Benchmark created by Dan Manastireanu on


Preparation HTML

<div id="test">
<p>some text</p>
<p>some other text</p>
<p>nothing</p>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script>
  var $div = $('#test'),
      withCheck = function(text) {
    if ($div.children(':contains("' + text + '")') === 0) {
     $div.empty();
    }
    $div.append('<p>' + text + '</p>');
      },
      withoutCheck = function(text) {
    $div.empty().append('<p>' + text + '</p>');
      };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
with check - found
withCheck('text');
ready
with check - not found
withCheck('not found');
ready
without check - found
withoutCheck('text');
ready
without check - not found
withoutCheck('not found');
ready

Revisions

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

  • Revision 1: published by Dan Manastireanu on