0

We have a piece of html that we are using to create an object that we pass into a function that clones data.

We are trying to get that cloned data and replace a common id with a new id that has been dynamically set elsewhere. below is what we have got:

// This is the cloned data we have got    
   var data = this.$container.find('.fields').clone();

// This is the id we are getting to find in the cloned html above
    var id = this.$container.data('id');

// This is where we need to go through all html and replace the id above in here with whatever we need
    var replacedHtml = data.innerHtml().replace(id,'test');

// the cloneVariant function takes the data and does some good stuff with it. The $.parseHTML(replacedHtml) takes the string html and makes the dom element that goes into the coneVariant function.

   this.matrix.cloneVariant(this.$container,$.parseHTML(t));

What I need to do is replace that found id in the html with a string.

Can this be done?

M dunbavan
  • 1,157
  • 5
  • 22
  • 57
  • https://stackoverflow.com/questions/347798/changing-an-elements-id-with-jquery something like this? – cloned Jul 04 '19 at 14:43

1 Answers1

0

You can use the [id] selector to find any element in the $container which has an id attribute, then provide a function to prop() to update. You need to do the latter to ensure that the id attributes remain unique, and that you don't duplicate them at all.

data.find('[id]').prop(id, function(i, id) {
  return id + '_' + i
});

It is worth noting, though, that having incremental id attributes, and dynamically generating id attributes at runtime is a bit of a code smell. It's generally a better idea to use common classes and then relate elements to each other using DOM traversal.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Yeah I know that this is not a good way to get it going but I am prototyping something to show that it works :) I wonder if you can apply the same logic to the html string and look for an id within that string of html and replace that? Eg If in the html we see `text-5789-edit, input-5789-image` and could be replaced with `text-2179-edit, input-2179-image` – M dunbavan Jul 04 '19 at 14:50
  • It's possible, but that's an even worse way to do it. You should never try and dissect HTML strings; always use a HTML parser, which is what the above is doing. – Rory McCrossan Jul 04 '19 at 14:50