开发者

Javascript Regex and getElementByID

I'm trying to search for all elements in a web page with a certain regex pattern.

I'm failing to understand how to utilize Javascript's regex object for this task. My plan was to collect all elements with a jQuery selector

开发者_如何学C$('div[id*="Prefix_"]');

Then further match the element ID in the collection with this

var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
//Then somehow match it. 
//If successful, modify the element in some way, then move onto next element.

An example ID would be "Prefix_25412_Suffix". Only the 5 digit number changes.

This looks terrible and probably doesn't work:

1) I'm not sure if I can store all of what jQuery's returned into a collection and then iterate through it. Is this possible?? If I could I could proceed with step two. But then...

2) What function would I be using for step 2? The regex examples all use String.match method. I don't believe something like element.id.match(); is valid?

Is there an elegant way to run through the elements identified with a specific regex and work with them? Something in the vein of C#

foreach (element e in ElementsCollectedFromIDRegexMatch) { //do stuff }


Just use the "filter" function:

$('div[id*=Prefix_]').filter(function() {
  return /^Prefix_\d+_Suffix$/.test(this.id);
}).each(function() {
  // whatever you need to do here
  // "this" will refer to each element to be processed
});

Using what jQuery returns as a collection and iterating through it is, in fact, the fundamental point of the whole library, so yes you can do that.

edit — a comment makes me realize that the initial selector with the "id" test is probably not useful; you could just operate on all the <div> elements on the page to start with, and let your own filtering pluck out the ones you really want.


You can use filter function. i.e:

$('div[id*="Prefix_"]').filter(function(){
 return this.id.match(/Prefix_\d+_Suffix/);
}); 


You could do something like

$('div[id*="Prefix_"]').each(function(){
  if($(this).attr('id').search(/do your regex here/) != -1) {
   //change the dom element here
 }
});


You could try using the filter method, to do something like this...

var pattern = /Prefix_/ + [0 - 9]+ + /_Suffix$/;
$('div[id*="Prefix_"]').filter(function(index)
    {
        return $(this).attr("id").search(pattern) != -1;
    }
);

... and return a jQuery collection that contains all (if any) of the elements which match your spec.

Can't be sure of the exact syntax, off the top of my head, but this should at least point you in the right direction

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜