Categories
JavaScript Answers

How to parse an HTML string with JavaScript?

Spread the love

To parse an HTML string with JavaScript, we create an element and put the HTML inside it.

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>";

const links = el.getElementsByTagName("a");

to call createElement to create the html element.

Then we set its innerHTML property to the HTML string we want to parse.

Next, we get the links from el with getElementsByTagName.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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