如何从DOMParser获取除外层body标签之外的所有HTML内容
DOM(文档对象模型)允许我们动态访问和操作HTML数据。使用DOMParser还可以提取HTML文件中的所有文本数据。DOM解析器返回一个HTML/XML/SVG对象。所有这些对象可以使用javascript中的[ ]运算符进行访问。
对象的HTML DOM树结构:
使用DOMParser从HTML文档中获取所有文本的步骤:
第一步: 声明一个DOMParser的实例。
const parser = new DOMParser();
第二步: 使用.parseFromString()函数解析文档。它接受两个参数,要解析的字符串和文档类型。
const parsedDocument = parser.parseFromString(
htmlInput, "text/html");
第三步: 使用doc.all元素访问整个HTML页面,现在获取其存储在0 的根元素。我们还可以使用getElementByID()来获取特定元素的内容。
var allText = parsedDocument.all[0].textContent;
最后,我们将使用doc.all[0]的textContent属性来获取所有HTML元素中的文本。
示例:
<title>This is the title</title>
<div>
<span>Geeks for geeks</span>
<p>Content to be parsed </p>
</div>
输出:
This is the title
Geeks for geeks
Content to be parsed
示例:
<h2>
DomParser to get
all HTML content
</h2>
<p>
Click on the button Below
to parse the HTML document
</p>
<!-- Paragraph element to
show the output -->
<p id="output"> </p>
<!-- Button to call the
parsing function -->
<button onclick="printOutput()">
Parse now
</button>
<script>
// Input HTML string to be parsed
var htmlInput = `
<title> This is the title </title>
<div>
<span>Geeks for geeks</span>
<p> Content to be parsed </p>
</div>
`;
// Created instance
const parser = new DOMParser();
// Parsing
const parsedDocument =
parser.parseFromString(
htmlInput, "text/html");
// Getting text
function printOutput() {
var allText = parsedDocument
.all[0].textContent;
// Printing on page and console
document.getElementById("output")
.innerHTML = allText;
console.log(parsedDocument
.all[0].textContent);
}
</script>
输出:
通过使用getElementsByClassName(’className’)和getElementById(’IDName’)也可以检索单个组件的文本内容。
将文档作为字符串解析并打印结果的Javascript函数。
function parse(htmlInput) {
// Creating Parser instance
const parser = new DOMParser();
// Parsing the document using DOM Parser
// and storing the returned HTML object in
// a variable
const parsedDocument = parser
.parseFromString(htmlInput, "text/html");
// Retrieve all text content from DOM object
var allText = parsedDocument.all[0].textContent;
// Printing the output to webpage and
console.log(parsedDocument.all[0].textContent);
}