// 使用 JavaScript 解析 HTML 的示例代码
// 假设我们有一个 HTML 字符串
const htmlString = `
<div>
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</div>
`;
// 方法一:使用 DOMParser
const parser = new DOMParser();
const doc = parser.parseFromString(htmlString, 'text/html');
// 获取 h1 元素的内容
const h1Element = doc.querySelector('h1');
console.log(h1Element.textContent); // 输出: Hello World
// 获取 p 元素的内容
const pElement = doc.querySelector('p');
console.log(pElement.textContent); // 输出: This is a paragraph.
// 方法二:使用 innerHTML 和 createElement
const tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
// 获取 h1 元素的内容
const h1Element2 = tempDiv.querySelector('h1');
console.log(h1Element2.textContent); // 输出: Hello World
// 获取 p 元素的内容
const pElement2 = tempDiv.querySelector('p');
console.log(pElement2.textContent); // 输出: This is a paragraph.
DOMParser,我们可以将 HTML 字符串解析为一个完整的文档对象模型(DOM),然后可以像操作普通网页一样查询和操作这些元素。div 元素,并将其 innerHTML 设置为 HTML 字符串,我们可以轻松地访问和操作其中的元素。这两种方法都可以有效地解析 HTML 字符串,并根据需要提取或修改其中的内容。
上一篇:js 添加html
下一篇:js 自动滚动
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站