Aju John
Aju John

Reputation: 2244

How to show html element as text in webpage

I want to loop this array and show the data into a table.

var dataM = [
          {
              "id": "1",
              "name": "My #1",
              "thumbnailUrl": "image/8.gif",
              "price": 20
            },
            {
              "id": "2",
              "name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
              "url": "image/10.gif",
              "price": 10
            }
        ];

Javascript function :

function loadData() {
  var data = "";
  for(var i = 0; i < dataM.length; i++) {
    data += "<tr>";
    var tempData = dataM[i];

    Object.keys(tempData).forEach(function(key) {
        data += "<td><code>" + tempData[key] + "</code></td>";
    });
    data += "</tr>";
  }
  var tbody = document.getElementsByTagName('tbody');
  tbody[0].innerHTML = data;
}

Upvotes: 0

Views: 123

Answers (1)

Ele
Ele

Reputation: 33736

How to show HTML element as text in webpage?

Create elements and use innerText attribute.

var dataM = [{
    "id": "1",
    "name": "My #1",
    "thumbnailUrl": "image/8.gif",
    "price": 20
  },
  {
    "id": "2",
    "name": "<img onerror='window.document.body.innerHTML = \"<h1>XSS</h1>\";' src=''> ",
    "url": "image/10.gif",
    "price": 10
  }
];

function loadData() {
  var tbody = document.getElementsByTagName('tbody')[0];
  for (var i = 0; i < dataM.length; i++) {
    var tr = document.createElement('tr');
    var tempData = dataM[i];

    Object.keys(tempData).forEach(function(key) {
      var td = document.createElement('td');
      var code = document.createElement('code');
      
      code.innerText = tempData[key];
      
      td.appendChild(code);
      tr.appendChild(td);
    });

    tbody.appendChild(tr);
  }
}

loadData();
<table>
  <tbody>
  </tbody>
</table>

Upvotes: 1

Related Questions