[javascript] jQuery selector for id starts with specific text

I have this jQuery code:

$( "#editDialog" ).dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "explode",
    duration: 1000
  }
});

But I have several divs with id's like this: editDialog-0, editDialog-1, ...., editDialog-n.

How can I make a jQuery code for all of these divs, like the one above?

This question is related to javascript jquery

The answer is


Add a common class to all the div. For example add foo to all the divs.

$('.foo').each(function () {
   $(this).dialog({
    autoOpen: false,
    show: {
      effect: "blind",
      duration: 1000
    },
    hide: {
      effect: "explode",
      duration: 1000
    }
  });
});

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

Let me offer a more extensive answer considering things that you haven't mentioned as yet but will find useful.

For your current problem the answer is

$("div[id^='editDialog']");

The caret (^) is taken from regular expressions and means starts with.

Solution 1

// Select elems where 'attribute' ends with 'Dialog'
$("[attribute$='Dialog']"); 

// Selects all divs where attribute is NOT equal to value    
$("div[attribute!='value']"); 

// Select all elements that have an attribute whose value is like
$("[attribute*='value']"); 

// Select all elements that have an attribute whose value has the word foobar
$("[attribute~='foobar']"); 

// Select all elements that have an attribute whose value starts with 'foo' and ends
//  with 'bar'
$("[attribute^='foo'][attribute$='bar']");

attribute in the code above can be changed to any attribute that an element may have, such as href, name, id or src.

Solution 2

Use classes

// Matches all items that have the class 'classname'
$(".className");

// Matches all divs that have the class 'classname'
$("div.className");

Solution 3

List them (also noted in previous answers)

$("#id1,#id2,#id3");

Solution 4

For when you improve, regular expression (Never actually used these, solution one has always been sufficient, but you never know!

// Matches all elements whose id takes the form editDialog-{one_or_more_integers}
$('div').filter(function () {this.id.match(/editDialog\-\d+/)});