开发者

Iterate through elements with similar IDs

开发者 https://www.devze.com 2023-02-22 06:03 出处:网络
I want to get the id of a single <span> element during iterati开发者_运维知识库on. Example scenario:

I want to get the id of a single <span> element during iterati开发者_运维知识库on.

Example scenario:

I have a few ids which start with AAA and end with BBB. The middle characters can vary:

 <span id="AAA-LS-BBB">hi1</span>
 <span id="AAA-LAS-BBB">hi2</span>
 <span id="AAA-LBS-BBB">hi3</span>
 <span id="AAA--LCS--BBB">hi4</span>

Here, first 3 digits of span id and last 3 digits of span id is same...only in middle it will vary. I want to generalized method to know ...each id using... $("#id").attr("id") so, here I am trying to find out iteration like below, I want to write one iterator method to get the current id

$("span[id^='AAA-***-BBB']").each(function(){
    var a = $("this").attr("id");
});

Hope my requirements are clear. how ti use regular expression here.. to find out id?


Use .filter() combined with a regex:

$('span[id]').filter(function () {
    return /^AAA.*BBB$/.test(this.id);
}).each(function () {
    alert(this.id);
});

Alternatively, since you are using a .each() already, you can simply add an if condition inside it:

$('span[id]').each(function () {
    if (/^AAA.*BBB$/.test(this.id)) {
        alert(this.id);
    }
});

Update: It looks like you can also combine both the Attribute-Starts-With and Attribute-Ends-With selectors on the same attribute:

$('div[id^="AAA"][id$="BBB"]').each(function () {
    alert(this.id);
});

(See example: http://jsfiddle.net/2pz8X/)


Combining fellow contributors' suggestions, and making the regex more specific:

// first, at least get all <div>'s with id's that start with 'AAA'
$("div[id^='AAA']").filter(function(){ 
    var regexp = /^A{3}(.*)B{3}$/; // regex
    return (this.id.match(regexp));
});

This will return all the div's that you need to target.

Sample @ http://jsfiddle.net/4ZNWJ/


Try this:

$("span[id^='AAA']").each(function(){
  alert($(this).id);
});
0

精彩评论

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