dom to html,Convert an HTML file to a DOM document
时间: 2024-01-22 12:04:23 浏览: 23
To convert an HTML file to a DOM document in JavaScript, you can use the `DOMParser` API. Here's an example code snippet:
```javascript
// HTML string
const htmlString = '<html><head><title>My Page</title></head><body><p>Hello World!</p></body></html>';
// Create a new DOMParser object
const parser = new DOMParser();
// Parse the HTML string and create a DOM document
const doc = parser.parseFromString(htmlString, 'text/html');
// Access elements in the DOM document
const title = doc.querySelector('title').textContent; // "My Page"
const body = doc.querySelector('body').innerHTML; // "<p>Hello World!</p>"
```
In this example, we first define an HTML string. We then create a new `DOMParser` object and use its `parseFromString` method to parse the HTML string and create a new DOM document. Finally, we can access elements in the DOM document using standard DOM methods such as `querySelector`.