html-document-fragment-element
v1.0.1
Published
A simple custom element that does like a DocumentFragment.
Downloads
14
Maintainers
Readme
<document-fragment>
The document fragment custom element is a simple custom element that does like a DocumentFragment.
Usage
In browser
<!DOCTYPE html>
<html>
<head>
<title>html-document-fragment-element in the browser</title>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lib/index.min.js"></script>
</head>
<body>
<script>
// code...
</script>
</body>
</html>
Support browser
- Chrome
- Safari
- Firefox
- Edge
In development
Installation:
npm install --save html-document-fragment-element
Use replaceWith with some elements
html:
<element class="target"></element>
js:
import 'html-document-fragment-element';
const target = document.querySelector('.target');
const dfElm = document.createElement('document-fragment');
dfElm.insertAdjacentHTML('afterbegin', `
<document-fragment>
<p>element 1</p>
<p>element 2</p>
</document-fragment>
`);
target.replaceWith(dfElm);
Result HTML:
<p>element 1</p>
<p>element 2</p>
Parse the string as DOM then append to the page.
This is example of way to add two p elements as children of the body element.
Usually:
const markup = `
<p>element 1</p>
<p>element 2</p>
`
const parser = new DOMParser();
const {body} = parser.parseFromString(markup, 'text/html');
for (const p of [...body.childNodes]) {
document.body.append(p);
}
With HTMLDocumentFragmentElement:
import 'html-document-fragment-element';
const markup = `
<p>element 1</p>
<p>element 2</p>
`
const dfElm = document.createElement('document-fragment');
dfElm.insertAdjacentHTML('afterbegin', markup);
document.body.append(dfElm);
Use as constructor
import { HTMLDocumentFragmentElement } from 'html-document-fragment-element';
const dfElm = new HTMLDocumentFragmentElement();
Syntax
new HTMLDocumentFragmentElement(content, [...content]);
new HTMLDocumentFragmentElement(contents);
Parameters
Arguments are implicitly converted to strings if they are not objects.
content
The element is initialized with the given string
or Node
as childNode
.
contents
The element is initialized with the given something as childNode
.
The types are allowed string
, Node
, NodeList
, HTMLCollection
and arrays containing them.
Contributing
- Fork it!
- Create your feature branch:
git checkout -b my-new-feature
- Commit your changes:
git commit -am 'Add some feature'
- Push to the branch:
git push origin my-new-feature
- Submit a pull request :D
License
MIT