AlexShevyakov
AlexShevyakov

Reputation: 423

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.

Upvotes: 3

Views: 6285

Answers (3)

Bradley Trager
Bradley Trager

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

DEMO

Upvotes: 4

tewathia
tewathia

Reputation: 7298

Use the jQuery filter method.

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

DEMO

Upvotes: 6

kei
kei

Reputation: 20491

DEMO

document.querySelectorAll('[id^=Q]').length

caveat: [id^=Q] includes IDs that start with 'Q' so id="Question" will also be included.

Upvotes: 3

Related Questions