Search code examples
javascriptjqueryckeditor

Return object bound to a dynamic element when label for object is also dynamic


I am using CKEditor. Within my page, the user can dynamically add/remove the element containing the WYSIWYG ckeditor text editor.

CKEDITOR.instances returns an object which contains within it all the ck_editor objects on my page.

When the user clicks the add button, then the following code successfully grabs that element:

CKEDITOR.instances[“my_textarea_0_body"]

The issue is when the user clicks delete to remove that element, and then reclicks add. I now want to grab that new ckeditor element on the page. However, now I need to grab it with this:

CKEDITOR.instances[“my_textarea_1_body"]

Notice that the number changed. So, the user is able to toggle the add/remove of this element any number of times. Example: if they did it 100 times I would need to have a way to grab that object like so:

CKEDITOR.instances[“my_textarea_100_body"]

The problem is that I never know what that number will be. That number is vital for me to create the string in order to grab the appropriate object.

Question: How can I grab this dynamically labeled object that is contained within the CKEDITOR.instances object? I know that my desired object will always be the LAST object appended within that CKEDITOR.instances object.


Solution

  • I assume that CKEDITOR.instancess a kind of a map (dictionary), so you can get all key names by Object.keys(). And then select the last/first/ or n-th instance name.

    var mapping_length = Object.keys(CKEDITOR.instances).length;
    var object_label   = Object.keys(CKEDITOR.instances)[mapping_length - 1];
    CKEDITOR.instances[object_label];
    

    This will return the desired object from within that dictionary object.