How to parse an HTML string with JavaScript?

Spread the love

Sometimes, we want to parse an HTML string with JavaScript.

In this article, we’ll look at how to parse an HTML string with JavaScript.

How to parse an HTML string with JavaScript?

To parse an HTML string with JavaScript, we can put the HTML string in an element.

For instance, we write

const el = document.createElement("html");
el.innerHTML = `
<html>
  <head>
    <title>titleTest</title>
  </head>
  <body>
    <a href="test0">test01</a><a href="test1">test02</a
    ><a href="test2">test03</a>
  </body>
</html>
`;

el.getElementsByTagName("a");

to create the html element with createElement.

Then we set its innerHTML property to an HTML stringg.

And then we select all the a elements from the string with getElementsByTagName.

Conclusion

To parse an HTML string with JavaScript, we can put the HTML string in an element.

Leave a Reply

Your email address will not be published. Required fields are marked *