开发者

Get array of ids from e.g xx_numbers

开发者 https://www.devze.com 2023-02-10 18:55 出处:网络
How can I retrieve an array of ids with only a prefix in common? E.g. I\'ve got a list of say 50 divs and they all got and ID looking like: aa_0000. Where \'a\' is a prefix and \'0\' represents rando

How can I retrieve an array of ids with only a prefix in common?

E.g. I've got a list of say 50 divs and they all got and ID looking like: aa_0000. Where 'a' is a prefix and '0' represents random numbe开发者_Go百科rs.


You want all elements of which their id starts with something common?

Assuming they are all div elements, this should work....

// Just so we can stay DRY :)
var prefix = 'aa_',
    matchElement = 'div';

// Do we have an awesome browser?
if ('querySelectorAll' in document) {
    var matchedDivs = document.querySelectorAll(matchElement + '[id^="' + prefix + '"]');
} else {
    var allDivs = document.getElementsByTagName(matchElement),
        matchedDivs = [],
        regex = new RegExp('^' + prefix);

    for (var i = 0, allDivsLength = allDivs.length; i < allDivsLength; i++) {
       var element = allDivs[i];
       if (element.id.match(regex)) {
           matchedDivs.push(element);
       }
    }
}

console.log(matchedDivs.length); // Expect 3

jsFiddle.

If you want to explicitly match ones with numbers, try the regex /^aa_\d+$/.

If you have jQuery floating around, you can use $('div[id^="aa__"]').


For people using jQuery:

$('div[id^="aa_"]')
0

精彩评论

暂无评论...
验证码 换一张
取 消