jQuery: Giving each matched element an unique ID

13,900

Solution 1

My take was to generate a random number and append it to the initial id:

jQuery.noConflict();
jQuery(window).ready(function() {

   var myQ1 = jQuery("input[id*='test']");
   var uniqueNum = Math.floor( Math.random()*99999 );
   var uniqueID = myQ1.attr('id')+'-'+String(uniqueNum);

   myClone=myQ1.clone();
   myClone.text('Replaced this button');

   myQ1.replaceWith('<span id='uniqueID+'></span>');

   jQuery('#'+uniqueID).append(myClone);

});

Solution 2

That's good stuff, thanks to all! In the end it looks like:

var myQ1 = jQuery("input[name~=test1]");
myQ1.each(function() {
    var id = Math.floor( Math.random()*99999 );
    jQuery(this).wrap("<span id=\"span-"+id+"\"></span>");
...

Aseptik, there is a lot more code, much more than I drug into this, so I wanted to keep the part I was hung up on brief. Thanks again for the input.

Regards, Aaron

Share:
13,900
Admin
Author by

Admin

Updated on June 05, 2022

Comments

  • Admin
    Admin about 2 years

    I am writing an 'inline translator' application to be used with a cloud computing platform to extend non-supported languages. The majority of this uses jQuery to find the text value, replace it with the translation, then append the element with a span tag that has an unique ID, to be used elsewhere within the application. The problem arises however, when there are more than one element, say , that have the exact same value to be translated (matched elements). What happens in the function in question is that it puts all matched elements in the same span, taking the second, third, fourth, etc. out of their parent tags. My code is pretty much like this example:

    <script src='jquery-1.4.2.js'></script>
    <script>
    jQuery.noConflict();
    var uniqueID='asdfjkl';
    jQuery(window).ready(function() {
    var myQ1 = jQuery("input[id~=test1]");
    myClone=myQ1.clone();
    myClone.val('Replaced this button');
    myQ1.replaceWith('<span id='+uniqueID+'></span>');
    jQuery('#'+uniqueID).append(myClone);
    });
    </script>
    <table>
    <tr><td>
    <input id='test1' type='button' value="I'm a button!"></input> &nbsp;
    <input id='test2' type='button' value="And so am I"></input>
    </tr></td>
    <tr><td>
    <input id='test1' type='button' value="I'm a button!"></input>
    </tr></td>
    </table>
    

    As a workaround, I've experimented with using a loop to create a class for each span, rising in increment until jQuery("input[id~=test1]").length, but I can't seem to get anything I do to work. Is there any way to give each matched element an unique ID? My fluency in jQuery is being put to the test!

    Thanks for any help in advance.

    Aaron