1

When I pass an array of objects as arguments to a function in script, I don't face any problem. But, problem occurs when I try to do the same thing while dynamically rendering some html. I get the following error - "Uncaught SyntaxError: Unexpected identifier". To be a little bit more specific, error occurs when I click rendered bottun I get "rend2([object Object],[object Object]) in my console"

const arri = [obj, obj2];

function rend(data) {
  console.log(data);
  let html;
  let content = document.getElementById('my-list');
  html = '<button onclick="rend2(' + data + ')">click</button>';
  content.insertAdjacentHTML('beforeend', html);
  console.log('obj', data);
}

function rend2(obj) {
  console.log('obj', obj);
}
  • What html is generated from this? Also when do you get this error? – Sergio Tulentsev Apr 08 '19 at 07:48
  • @SergioTulentsev this is just for testing example, it generated button with onclick event listener, problem is when i pass data object as argument, html is not the problem –  Apr 08 '19 at 07:51
  • 1
    You're funnelling everything through a text representation, so at the very least you'd need to `JSON.stringify` your object to preserve it in text representation. Really though you should not be producing HTML at all, but create DOM elements and event listeners and work with native functions and objects. See the duplicates. – deceze Apr 08 '19 at 08:26
  • @SergioTulentsev thank you for information, I'll check those answers. –  Apr 08 '19 at 08:34