Ciaran Gaffey
Ciaran Gaffey

Reputation: 89

Allow javascript to work on div with any number appended to it

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?

Upvotes: 0

Views: 161

Answers (6)

A. Wolff
A. Wolff

Reputation: 74420

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

$('div[id^="activity-accordion"]').accordion({
    collapsible: true,
    heightStyle: "content",
    active: false,
    header: "h3",
    navigation: true
});

Upvotes: 0

techfoobar
techfoobar

Reputation: 66693

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({
    ...
});

Upvotes: 0

user2188149
user2188149

Reputation:

use a class would be more didactic and correct to do

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

Upvotes: 0

stackptr
stackptr

Reputation: 177

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.

Upvotes: 0

reyaner
reyaner

Reputation: 2819

you could select them like this:

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

Selects all div, that starts with activity-accordion

Upvotes: 1

Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10179

Use this css selector: *=

$(function() {
    $( "[id*='activity-accordion']" ).accordion({
         collapsible: true,
         heightStyle: "content",
         active: false,
         header: "h3",
         navigation: true
    }); 
});

Upvotes: 1

Related Questions