chobo2 chobo2 - 1 year ago 87
jQuery Question

How can I get a jquery ui dialog object?

Say I have a dialog open that has no "id" how can I find the dialog and get the dialog object so I can do .dialog('close') on it?


// say if this was my dialog
<input type="button" id="btn" />


This does not work though so I need to get the actual object.

Answer Source

That's the very reason you should have an id on those divs. Consider the following options:

  1. Consider adding the id to the markup. That is easy to do and maintain.

  2. Otherwise, when you get the div(s) originally, before performing a .dialog(), give them dynamic id's: el.attr('id', 'dialogBox').

  3. If you don't want to give them id's (for some strange reason), you still have them at some point in time in your js code, so save the references to those objects. Later on, refer to the required reference and you can call .dialog('close'). That will also perform caching for you, so you don't need to search the DOM tree again.

  4. As a last resort, if you don't want to do the above, then refer to them the same way you did originally (this isn't always a good idea, especially if the DOM changes).

Although just for reference, your example (which employs the last option) works: