Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of elements with specific ID pattern

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.

like image 485
AlexShevyakov Avatar asked Jan 26 '26 17:01

AlexShevyakov


2 Answers

Use the jQuery filter method.

$('*').filter(function () {
    return this.id.match(/Q\d+/); //regex for the pattern "Q followed by a number"
}).length;

DEMO

like image 146
tewathia Avatar answered Jan 29 '26 08:01

tewathia


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);
});

DEMO

like image 40
Bradley Trager Avatar answered Jan 29 '26 07:01

Bradley Trager