3

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.

AlexShevyakov
  • 425
  • 7
  • 18

3 Answers3

6

Use the jQuery filter method.

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

DEMO

tewathia
  • 6,890
  • 3
  • 22
  • 27
4

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

Bradley Trager
  • 3,570
  • 3
  • 26
  • 33
  • 1
    It might not be necessary, depending on what the actual values will be, but you might want to use `/Q\d+$/` for the regex. The "starts with" selector will insure that the values start with "Q", but, without the `$` at the end of the regex, you could end up with IDs that have other characters after the numbers. – talemyn Mar 07 '14 at 17:56
3

DEMO

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

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

kei
  • 20,157
  • 2
  • 35
  • 62