Reputation: 423
I would like to use javascript to count all elements that have ID pattern like:
"Q"+Number
and return the result into a text field "result".
Say, we have the following example:
<div>
<div id="Q01">
<p>Some text</p>
</div>
<div id="Q02">
<p>Some text</p>
</div>
<div id="Q03">
<p>Some text</p>
</div>
<label for="number">Number of DIVs:</label>
<input type="number" name="result" id="number">
</div>
Thanks in advance.
Upvotes: 3
Views: 6285
Reputation: 3590
I know this has been answered, but here is an improvement on @kei's answer. Instead of filtering all DOM elements using $('*')
, first narrow it down to only elements with id starting with a "Q". Another modification as suggested by @talemyn is to add a $
to the end of the regex in order to ensure that there are no characters following the digits.
$(function () {
var result = $('[id^=Q]').filter(function () {
return this.id.match(/Q\d+$/); //regex for the pattern "Q followed by a number"
}).length;
$('input[name=result]').val(result);
});
Upvotes: 4