A very simple browser script to parse html strings into document fragments.
Install the package with yarn or npm.
yarn add string-to-html
# Or use npm
npm install string-to-htmlIf you want to use this directly in your browser download and include the dist/string-to-html.js file in a script tag on your page.
<script src="./string-to-html.js"><script>Example usage:
import toHtml from 'string-to-html'; // Omit this line if you use the es5 version.
const people = ['Alfred', 'Jodocus', 'Kwak', 'Dolf'];
const htmlString = `
<ul>
${ people.map(name => `<li>${ name }</li>`).join('') }
</ul>
`;
const fragment = toHtml(htmlString);
document.body.appendChild(fragment);For when you want to use vanilla JS and parse html strings into a DOM fragments. It's saves a time and is much easier than using document.createFragment() and appending document.createElement() as child elements.
Why a domfragment instead of innerHTML ? Because you can do DOM operations on the fragment before inserting in into the document.
- Install depedencies with
yarn install. - To bundle and transpile run
yarn buildthis will output a transpiled, common js and es2015 module version ofstring-to-html.jsto thedist/directory. - Run tests with
yarn testor opentest.htmlin your browser after runningyarn build-test.