0

I have a small bit of jquery that applies the jquery-ui accordian to an array of divs.

The divs are generated dynamically and each one needs to have a unique ID. I have successfully generated unique IDs for divs with each one having a different number at the end. Now I would like the jquery to be flexible enough to handle any of the divs no matter what number is at the end. All the divs have IDs with the naming convention "activity-accordion123" or "activity-accordian+number"

Here is the code I am using currently for the divs that have already been generated:

$(function() {
    $( "#activity-accordion408,#activity-accordion410,#activity-accordion415,#activity-accordion428,#activity-accordion439,#activity-accordion427" ).accordion({
      collapsible: true,
heightStyle: "content",
active: false,
header: "h3",
navigation: true
    }); 
  });

I would like to change this javascript so that it will work with any div that has the ID of "activity-accordion+any number". Is this possible?

6 Answers6

1

Use this css selector: *=

$(function() {
    $( "[id*='activity-accordion']" ).accordion({
         collapsible: true,
         heightStyle: "content",
         active: false,
         header: "h3",
         navigation: true
    }); 
});
Mohammad Areeb Siddiqui
  • 9,795
  • 14
  • 71
  • 113
1

you could select them like this:

$("div[id^='activity-accordion'"])

Selects all div, that starts with activity-accordion

reyaner
  • 2,799
  • 1
  • 12
  • 17
0

Use ID attribute selector wildcard 'start with' like that:

$('div[id^="activity-accordion"]').accordion({
    collapsible: true,
    heightStyle: "content",
    active: false,
    header: "h3",
    navigation: true
});
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
0

Is there any reason that you can not simply have each div possess an "activity-accordion" class? Classes are useful to style/manipulate multiple similar elements. You can then use $('.activity-accordion') to select all such elements.

stackptr
  • 167
  • 1
  • 2
  • 10
  • Yes I thought of that but the jquery-ui accordion, if to be repeated on one page, needs to be applied to divs with unique IDs/Classes. As far as I could understand. – Ciaran Gaffey Jul 19 '13 at 13:16
0

use a class would be more didactic and correct to do

$(function() {
    $( ".accordions" ).accordion({
      collapsible: true,
heightStyle: "content",
active: false,
header: "h3",
navigation: true
    }); 
  });
0

To match all <div>s, with an id of the pattern activity-accordion<number>, you can use:

$('div').filter(function() {
    return /activity\-accordion\d+/.test(this.id);
}).accordion({
    ...
});
techfoobar
  • 65,616
  • 14
  • 114
  • 135