164

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?

informatik01
  • 16,038
  • 10
  • 74
  • 104
progNewbie
  • 4,362
  • 9
  • 48
  • 107

4 Answers4

319

Use jquery starts with attribute selector

$('[id^=editDialog]')

Alternative solution - 1 (highly recommended)

A cleaner solution is to add a common class to each of the divs & use

$('.commonClass').

But you can use the first one if html markup is not in your hands & cannot change it for some reason.

Alternative solution - 2 (not recommended if n is a large number) (as per @Mihai Stancu's suggestion)

$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')

Note: If there are 2 or 3 selectors and if the list doesn't change, this is probably a viable solution but it is not extensible because we have to update the selectors when there is a new ID in town.

Venkata Krishna
  • 14,926
  • 5
  • 42
  • 56
  • 3
    @Krishna for the sake of completeness if you would like to add my comment to your answer (listing multiple CSS selectors): `jQuery('#anID1, #anID2, #anID2')` – Mihai Stancu Apr 22 '14 at 15:27
  • Does anyone know, how i can get this code work if i load the div boxes with ajax ? – progNewbie Apr 22 '14 at 15:45
  • http://stackoverflow.com/questions/23224396/get-jquery-dialog-working-when-loading-content-with-ajax – progNewbie Apr 22 '14 at 15:54
  • Avoid Selecting by Class Only: $(".myclass"); will run quickly in modern browsers. Unfortunately, in older browser such as IE6/7 and Firefox 2, jQuery must examine every element on the page to determine whether “myclass” has been applied. The selector will be more efficient if we qualify it with a tag name, e.g. : $("div.myclass"); – Reza Baradaran Gazorisangi Oct 10 '15 at 20:05
  • `$('#editDialog-0, #editDialog-1, #editDialog-2,...,#editDialog-n')` might also be written as `$('#editDialog-0').add('#editDialog-1').add('#editDialog-2')` etc for `('#editDialog-n')` Note I would likely seek another solution than this for any set beyond trivial length. – Mark Schultheiss Jul 26 '17 at 14:33
62

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+/)});
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Luke Madhanga
  • 6,871
  • 2
  • 43
  • 47
  • As an alternative for `$("[attribute^='foo'][attribute$='bar']");` - what this says is find all attributes that end with "bar" then within that set find those that start with "foo" due to the right to left processing of the sizzle. Perhaps a refinement might be `$("[attribute^='foo']").filter("[attribute$='bar']");` which allows you to isolate the begin with "foo" and then select within that set with the suffix "bar" - which might be faster. Results are dependent on your DOM and frequency of each. – Mark Schultheiss Jul 26 '17 at 14:29
8

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")
dcendents
  • 753
  • 5
  • 7
3

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
    }
  });
});
Selvaraj M A
  • 3,096
  • 3
  • 30
  • 46
  • Either that or list the ids in the jQuery selector: `jQuery('#myid1, #myid2, #myid3')`. – Mihai Stancu Apr 22 '14 at 15:18
  • This requires a change to the HTML, which isn't strictly necessary. – isherwood Apr 22 '14 at 15:18
  • @Mihai Stancu, what if there are 368 IDs? – isherwood Apr 22 '14 at 15:19
  • 1
    Maybe so, but if you have to enumerate the id's, you likely didn't need id's in the first place. – Kevin B Apr 22 '14 at 15:19
  • 3
    @isherwood what you're saying is true, but it's a recommended way to do things -- if they have common functionality they should also have common classes. – Mihai Stancu Apr 22 '14 at 15:19
  • @Kevin and Mihai... Agreed, but you're making assumptions about the OP's scenario. – isherwood Apr 22 '14 at 15:21
  • @isherwood as I said, it is just "another" way to do it. It is comfortable to do it for a few ids, if we're talking about 368 IDs it'd cumbersome to use this, and I'd recommend Selvaraj's answer using classes. – Mihai Stancu Apr 22 '14 at 15:21
  • I just suggested **another** scenario that Selvaraj could add to his answer to make the answer more complete and to help future readers find answers no matter the scenario. – Mihai Stancu Apr 22 '14 at 15:25
  • No need to make this a personal thing. I don't comment "against people". I simply share ideas about the code. As I said, I agree with your solution, but I find Krishna's answer more appropriate, so I voted for it. That's what we do on SO. :-) – isherwood Apr 22 '14 at 15:49
  • @isherwood You were treating a comment like an answer, bringing (constructive) criticism to it as if it were an answer; it's just not a fair comparison because the comment section of StackOverflow has a different (complementary) role to the answers. – Mihai Stancu Apr 22 '14 at 21:28
  • @isherwood StackOverflow strives towards being the "one place to go to" for programming answers (to old and new questions) meaning that old answers become Wikis editable by the community having their titles / questions / answers corrected, improved, pruned, generalized, to make it more clear and useful to future visitors who won't have OPs particular context / precise-necessities. Because of this an answer which covers variants and alternatives is more valuable to the community. – Mihai Stancu Apr 22 '14 at 21:32