How to use the parseFragment function from parse5

Find comprehensive JavaScript parse5.parseFragment code examples handpicked from public code repositorys.

parse5.parseFragment is a function in the parse5 library that can parse an HTML fragment and return a document fragment.

597
598
599
600
601
602
603
604
605
606
    throw new CourseIssueError(
      `${elementFile}: Error calling ${phase}(): return value is not a string`,
      { data: ret_val, fatal: true }
    );
  }
  node = parse5.parseFragment(ret_val);
} else if (phase === 'file') {
  // Convert ret_val from base64 back to buffer (this always works,
  // whether or not ret_val is valid base64)
  const buf = Buffer.from(ret_val, 'base64');
fork icon250
star icon246
watch icon14

46
47
48
49
50
51
52
53
54
    console.log(LOG_PREFIX, 'File =>', file.path);
}

// Parse the the file content and get the tag content.
var contents = file.contents.toString(encoding),
    fragment = parse5.parseFragment(contents, {
        locationInfo: true
    }),
    tagContent = [];
fork icon3
star icon14
watch icon0

+ 3 other calls in file

How does parse5.parseFragment work?

parse5.parseFragment is a function in the parse5 library that parses a fragment of an HTML or XML document and returns an object representing the parsed structure.

It takes in two arguments - the fragment of the document to be parsed as a string, and an options object that can be used to customize the parsing behavior.

The parsed object returned by parse5.parseFragment represents the structure of the fragment as a tree of nodes, with each node being represented by an object with properties describing the node's name, attributes, child nodes, and other metadata.

87
88
89
90
91
92
93
94
95
96
{
  name: 'GIPHY',
  shouldTransform,
  getHTML: async url => {
    const html = await getHTML(url)
    const div = parse5.parseFragment(html).childNodes[0]
    if (div.nodeName === 'div') {
      div.attrs.push({
        name: 'class',
        value: 'giphy-embedder giphy-gif-embed',
fork icon0
star icon3
watch icon0

202
203
204
205
206
207
208
209
210
211
212
213
  const config = {
    ...ownerDocument._parseOptions,
    treeAdapter: new JSDOMParse5Adapter(ownerDocument, { fragment: true })
  };


  return parse5.parseFragment(contextElement, markup, config);
}


function parseIntoDocument(markup, ownerDocument) {
  const config = {
fork icon12
star icon1
watch icon1

Ai Example

1
2
3
4
5
6
7
const parse5 = require("parse5");

const htmlFragment = " Hello, world! ";

const parsedFragment = parse5.parseFragment(htmlFragment);

console.log(parsedFragment);

In this example, we're requiring the parse5 module, defining an HTML fragment as a string, and then passing it to parse5.parseFragment. The resulting parsed fragment is then logged to the console.

87
88
89
90
91
92
93
94
95
96

// generate css scope id
var id = '_v-' + hash(filePath || content)

// parse the file into an HTML tree
var fragment = parse5.parseFragment(content, { locationInfo: true })

// check node numbers
if (!validateNodeCount(fragment)) {
  return cb(new Error(
fork icon0
star icon0
watch icon1

+ 2 other calls in file

14
15
16
17
18
19
20
21
22
23
} catch (e) {
  assert(false, 'The BookList.vue file does not exist');
}

// Parse document
const doc = parse5.parseFragment(file.replace(/\n/g, ''), { locationInfo: true });
const nodes = doc.childNodes;

// Parse for HTML in template
const template = nodes.filter(node => node.nodeName === 'template');
fork icon0
star icon0
watch icon0

111
112
113
114
115
116
117
118
119
120
121


// Helper to traverse HTML tree
// nodeCallback(locId, locHint, node) is invoked for nodes
// attributeCallback(locId, locHint, attribute) is invoked for attributes
const traverseHtml = (contents, nodeCallback, attributeCallback, isFragment) => {
    const htmlTree = isFragment ? parse5.parseFragment(contents) : parse5.parse(contents);
    traverse(htmlTree, {
        pre(node, parent) {
            if (node.attrs) {
                // Check if content text should be localized based on presense of data-loc-id attribute
fork icon0
star icon0
watch icon0