I am creating two links dynamically, one using template literals and another using document.createElement(), in both I need to pass as an attribute data-presentation an object as a string of characters. But I get different results.
When I inspect the link created using template literals I get the following result
<a href="#" data-presentations="[{" name":"cremas","measures":["5g","15g"]}]"="">Click</a>
And because it is badly formed when I need to parse it, I get an error return.
On the other hand, the link created using document.createElement () upon inspection returns the following result.
<a href="#" data-presentations="[{"name":"Cremas","measures":["5g","15g"]}]">Another click</a>
And then when I need to parse it, it works properly.
Please take a look at the way are creatied the links
const root = document.querySelector('#root');
const object = {
"id": 4,
"name": "Medicine1",
"code": "1234",
"status": true,
"location": "E4-2",
"genericName": "SomeGenericName",
"presentations": [
{
"name": "Cremas",
"measures": [
"5g",
"15g"
]
}
]
};
const link = `<a href="#" data-presentations="${JSON.stringify(object.presentations)}">Click</a>`
const anchor = document.createElement('a');
anchor.href = '#';
anchor.setAttribute('data-presentations', JSON.stringify(object.presentations));
anchor.textContent = 'Another click';
root.innerHTML = link;
document.body.appendChild(anchor)
<div id="root"></div>
What can I do so that the link created through template literals is correctly formed?
JSONat HTML element attribute value.JSONcan be hardcoded at HTML as well. The only issue with the code at the question is the use of double quotes surrounding the attribute value within the template literal.