Select elements with data attribute

HTML

<script src="https://code.jquery.com/jquery-3.0.0.min.js"></script>
<div id="test" data-test="ok"></div>

<div id="test2"></div>

JavaScript

// Fill the first div with the amount of elements with the "test" data attibute, which is defined via markup
var test = $( '[data-test]' );
$( '#test' ).text( test.length );

// Fill the first div with the amount of elements with the "test2" data attibute, which is defined via jQuery
$( '#test2' ).data( 'test2', 'ok' );
var test2 = $( '[data-test2]' );
$( '#test2' ).text( test2.length );