0

I have the following JS code (with some jQuery) that prints errors from an array to bootstrap container:

var errors = [{
  "Message": "The source document is not valid. Please see the 'Schema 
Validation Issues' section above at column &1, line &2" 
}, {
  "Message": "The metadata element \"Resource Title\" is missing, empty or 
incomplete but it is required. Hint: \"A non-empty title is required for 
Spatial Data Sets and Spatial Data Set Series but none could be found.\"",
}, {
  "Message": "In content of element <CI_Citation>: The content model does not 
allow element <Q{.../gmd}date> to appear as the first child. It must be preceded by <Q{.../gmd}title>.  at column 31, line 73",
}];

$.each(errors, function(key, val) {
  var output = document.createElement("div");
  output.setAttribute("class", "alert alert-danger");
  output.innerHTML = '<strong>Error: </strong>'+val.Message;
  output.getElementById('container').appendChild(output);
});

Since some of my messages contain HTML/XML tags (see message 3.), they get printed as HTML instead of pure strings. How can I escape this? I need these messages printed as strings.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Marin Leontenko
  • 711
  • 2
  • 20
  • 26

1 Answers1

2

You should use innerText property as shown in the snippet example shown below.

var errors = [{
  "Message": "The source document is not valid. Please see the 'Schema Validation Issues' section above at column &1, line &2" 
}, {
  "Message": "The metadata element \"Resource Title\" is missing, empty or incomplete but it is required. Hint: \"A non-empty title is required for Spatial Data Sets and Spatial Data Set Series but none could be found.\"",
}, {
  "Message": "In content of element <CI_Citation>: The content model does not allow element <Q{.../gmd}date> to appear as the first child. It must be preceded by <Q{.../gmd}title>",
}];

$.each(errors, function(key, val) {
  var output = document.createElement("div");
  var outputText = document.createElement("div");

  output.setAttribute("class", "alert alert-danger");
  output.innerHTML = '<strong>Error: </strong>'+ val.Message;
    
  outputText.innerText = val.Message;
  document.getElementById('container').appendChild(output);
  document.getElementById('containerText').appendChild(outputText);    
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container"></div>
<br/><br/><br/>
<div id="containerText"></div>
Shiladitya
  • 12,003
  • 15
  • 25
  • 38
Amit Kumar Singh
  • 4,393
  • 2
  • 9
  • 22