1.0.1 • Published 3 years ago

html-document-fragment-element v1.0.1

Weekly downloads
-
License
MIT
Repository
github
Last release
3 years ago

<document-fragment>

MIT License Published on NPM Published on webcomponents.org npm.io Maintainability Test Coverage Known Vulnerabilities html-document-fragment-element

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/html-document-fragment-element@0.2.6/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

  1. Fork it!
  2. Create your feature branch: git checkout -b my-new-feature
  3. Commit your changes: git commit -am 'Add some feature'
  4. Push to the branch: git push origin my-new-feature
  5. Submit a pull request :D

License

MIT

1.0.1

3 years ago

0.2.6

3 years ago

0.2.5

3 years ago

0.2.4

3 years ago

0.2.3

3 years ago

0.2.2

3 years ago

0.2.1

3 years ago

0.2.0

3 years ago

0.1.0

3 years ago

1.0.0

3 years ago