乐闻世界logo
搜索文章和话题

How to parse an HTML string with JS

1个答案

1

When parsing HTML strings in JavaScript, we typically have several methods available. These methods can be selected based on specific use cases and requirements.

  1. Using DOMParser API: DOMParser is a Web API that allows parsing HTML or XML from a string. This method is suitable for scenarios where you need to parse a complete HTML string into a DOM tree for querying or manipulation.

    Example code:

    javascript
    const htmlString = '<div id="example">Hello, world!</div>'; const parser = new DOMParser(); const doc = parser.parseFromString(htmlString, 'text/html'); console.log(doc.body.innerHTML); // Output: <div id="example">Hello, world!</div>
  2. Directly using innerHTML: If you simply want to convert an HTML string into DOM elements and insert them into the existing DOM tree, you can use the innerHTML property.

    Example code:

    javascript
    const htmlString = '<div id="example">Hello, world!</div>'; const container = document.createElement('div'); container.innerHTML = htmlString; console.log(container.firstChild); // Output: the created div element
  3. Using jQuery (if included in the project): jQuery provides a convenient method $.parseHTML() that parses a string and returns an array of DOM nodes.

    Example code:

    javascript
    const htmlString = '<div id="example">Hello, world!</div>'; const htmlElements = $.parseHTML(htmlString); $(document.body).append(htmlElements); // Append the parsed elements to the body
  4. Using template elements: HTML5 introduced the

2024年8月22日 16:17 回复

你的答案