解析包含表格行的 html 片段

问题描述 投票:0回答:2

我从服务器返回了以下响应。这是一个html片段。 我想像这样用 DOMParser 解析它:

let responseText = '<div>Text Content</div><tr><td>Cell</td></tr>';
let doc = new DOMParser().parseFromString(`<body><template>${responseText}</template></body>`, 'text/html');
let fragment = doc.body.firstChild.content;

运行时的

fragment
变量包含以下DOM:

#document-fragment
  <div>Text Content</div>
  Cell

我的问题: 我希望它包含

<tr>
但它没有。如何更改解析代码以使其正确包含元素?

不允许我更改回复文本。

javascript html dom
2个回答
0
投票

tr 元素未被解析的原因是因为它不是模板元素的有效子元素。 template 元素只能包含在 HTML head 元素的上下文中有效的元素。

解析 tr 元素的一种可能解决方案是将其包装在 table 元素中,该元素是 body 元素的有效子元素。这是一个如何修改代码以解析 tr 元素的示例:

let responseText = '<div>Text Content</div><table><tbody><tr><td>Cell</td></tr></tbody></table>';

let doc = new DOMParser().parseFromString(

<body><template>${responseText}</template></body>
, 'text/html'); 让片段 = doc.body.firstChild.content;

在此修改后的代码中,tr 元素被包裹在 table 元素中,然后又被包裹在 tbody 元素中。这确保 tr 元素被 DOMParser 正确解析。请注意,您需要包含 tbody 元素以确保 tr 元素根据 HTML 规范有效。


0
投票

<tr>
只是
<table>
<thead>
<tbody>

的有效孩子

尝试将

<tr>
包裹在
<table>
中,然后使用
createContextualFragment
代替。

let responseText = '<div>Text Content</div><tr><td>Cell</td></tr>';
responseText = responseText
  .replace(/<tr>/, '<table>$0')
  .replace(/<\/tr>/, '$0</table>');

const fragment = document.createRange().createContextualFragment(responseText);
const cellContent = fragment.querySelector('td').innerText;

console.log(cellContent); // Cell
.as-console-wrapper { top: 0; max-height: 100% !important; }

© www.soinside.com 2019 - 2024. All rights reserved.