0

I have a variable that contains HTML.

var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>'+
'<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>'+
'<p>Testing</p>';

I am trying to loop around all of the elements and replace with spans specific date. So any spans with a class of variable-source will need to be replaced with specific date, and the same for input-source.

I have tried to use the following:

$('span', html).replaceWith(function () {
    var id = $(this).attr('id');
    // this returns the correct id
    //calculations go here
    var value = 'testing';
    return value
});

Which outputs the following:

testing This is a variable

All of the paragraph tags have been removed, and it seems to stop after the first paragraph. Is there something that I am missing here? I can post more code or explain more if needed.

Thanks in advance.

1 Answer 1

1

You need to create a html object reference, else you won't get a reference to the updated content. Then get the update content from the created jQuery object after doing the replace operations

var html = '<p><span id="variable:7" class="variable-source" title="variable:TEXT_CONTAINER">DATA</span> This is a variable</p>' +
  '<p><span id="input:10.New Input 2" class="input-source" title="New Screen; New Input 2">DATA</span> This is a input source</p>' +
  '<p>Testing</p>';

var $html = $('<div></div>', {
  html: html
});

$html.find('span.variable-source').replaceWith(function() {
  var id = this.id;
  // this returns the correct id
  //calculations go here
  var value = 'replaced variable for: ' + id;
  return value
});
$html.find('span.input-source').replaceWith(function() {
  var id = this.id;
  // this returns the correct id
  //calculations go here
  var value = 'replaced input for: ' + id;
  return value
});

var result = $html.html();
$('#result').text(result);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic this works! Thanks so much. I think my problem was not referencing the HTML object reference as you mentioned. I did do something like this a few hours ago but i removed it thinking it wouldn't work. Regardless, thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.