Pooshonk Pooshonk - 22 days ago 8
Javascript Question

Loop around HTML variable and replace spans with content

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.

Answer

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>

Comments