Wanted to share a technique I use quite a lot at the moment for dynamically naming elements in a loop or, more specifically for this method, in multiple nested loops.

Consider the following code which is pretty standard for most jquery modals at present.

To render these modals in a loop you might be familiar with the following code which I have seen a million times.  This set up makes sure that each link points to a corresponding container div with a matching unique id. Fine and dandy:

The problem with this method occurs when you are using this type of markup as a function or if you have some sort of dynamic setup where the above code may be outputted on the same page more than once. This would break the code as the link would just point to the first container div with that name.

I’ve seen setups with some very strange methods to get round this.

The Solution

Here is a simple solution that utilises php’s  uniqid function. This ensures you will NEVER get two id’s matching no mater how many nested loops you have going.

Implement it like so:

If you want to store the id’s of these for use at a later point, like I’ve done recently, you can do this:

Then you have access to the id’s later like so:

I’ve used this not just with modals, but when generating unique ids for other jQuery functions, when using with Advanced Custom Fields ‘Flexible Field’ addon to make sure all generated sections of content have a nice unique ids to point to.

More