First question ever! I’m stumped.
I have a web app which will, upon a user action, send a table row <tr>...</tr>
to the browser to replace a row that already exists. It works great, but the <tr>
element includes several dataset values that are used in Javascript, and when the table row is replaced in the document the values for the dataset properties retain the old values. I was looking for a way to update the values programmatically which led me to use DOMParser
and parseFromString()
to attempt to just use the resulting HTMLDocument to pluck out dataset values and use them. Example:
let content1 = `
<div id='div1' class='div-level-1' data-num='12345678'>
<div id='div2' class='div-level-2'>
<span id='span1' class='span-class'>
Span Content
</span>
</div>
</div>
`;
let content2 = `
<tr id='tr1' class='row-class' data-num='12345678'>
<td class='col-class'>
<span class='col-class'> </span>
</td>
<td class='col-class'>
Some Data in Col 2
</td>
<td class='col-class'>
<a target='_blank' href='http://SomeWebSite.com'>Some Web Site</a>
</td>
<td class='col-class'>
What is going on?
</td>
</tr>
`;
console.log(content1); // <-- Shows HTML fragment correctly
console.log(content2); // <-- Shows HTML fragment correctly
const parser1 = new DOMParser();
let parsed1 = parser1.parseFromString(content1, 'text/html');
let div1 = parsed1.getElementById('div1');
console.log(div1); // <-- Console shows HTML fragment as expected.
console.log(div1?.dataset?.num); // <-- Console shows 12345678
const parser2 = new DOMParser();
let parsed2 = parser1.parseFromString(content2, 'text/html');
let tr1 = parsed2.getElementById('tr1');
console.log(tr1); // <-- Console shows null.
console.log(tr1?.dataset?.num); // <-- Console shows undefined
Unless I’m nuts, parseFromString()
returns gibberish (well, a wrong result anyway) when used on a <tr>
element. Using it on a <div>
element works as expected: content1
works, k does not. I did not find any info on this. Anyone have ideas? Thanks!