开发者

how do i do a find to get any div that has an id that starts with a certain string

i have some dynamic code that will make a list of divs. i want to get back a list of items to loop through that have an id with the same start of the string.

开发者_如何学运维For example, i might have

<div id="table1" . . .
<div id="table2" . . .
<div id="table3" . . .

how, using jquery, can i get a list of all divs that have an id that starts with "table" ?


You can use an attribute selector for this.

$("div[id^='table']")...

The above means find all divs with an id that starts with "table".

Generally you want to avoid attribute selectors where possible however so if this is going to be something you do a lot I'd suggest changing your HTML:

<div id="table1" class="table" . . .
<div id="table2" class="table" . . .
<div id="table3" class="table" . . .

So you can simply do:

$("div.table")...

which will be much faster.

Update: You seem to have asked (in comments) regarding looping. For this use each():

$("div[id^='table']").each(function() {
  // `this` now refers to the current element
});


$('div[id^=table]')


$('div[id^=table]')

I think that should do it, from memory. It uses the ^, like in a regex.

So you don't ever accidentally select more then you bargain for, I'd add some more specificity to it. For example, you might have

$('#my-table div[id^=table]')

To then loop through them, use each()

    $('div[id^=table]').each(function() {
        $(this).append('<p>hello </p>');
});


$("[id]").filter(function() {
    return this.id.match(/^table[0-9]+$/);
});

Perhaps?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜