简体   繁体   中英

How does jQuery create DOM elements from string?

I'm trying to create an element from string, required for an external library (Trix editor by Bootcamp) to be implemented as a Vue component. Therefore, I've found the following snippet in the Trix issues :

let _ = require('lodash');

Vue.component('wysiwyg', {
  props: ['value'],
  template: '<div></div>',

  data() {
    return {
      trix: null,
      id: ''
    }
  },

  mounted() {
    this.id = _.sampleSize('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 5).join('');

    this.trix = $(`<trix-editor input="${this.id}"></trix-editor>`);

    let self = this;

    this.trix.on('trix-change', (e) => {
      self.$emit('input', e.currentTarget.innerHTML)
    });

    this.$watch('value', function(value) {
      value = value === undefined ? '' : value;
      if (self.trix[0].innerHTML !== value) {
        self.trix[0].editor.loadHTML(value);
      }
    });

    this.trix.insertAfter(this.$el);
  },
});

They use jQuery to create the element, which I'd like to avoid. Using template tags or a DOMParser , the library won't load - using $(template) though, everything works smoothly.
What is the difference between the following snippets and how to get things right?

I've tried several methods that fail:

  1. With createContextualFragment :

     let el = document .createRange() .createContextualFragment('<div class="foo"></div>') 
  2. With template tags:

     let template = document.createElement('template'); template.innerHTML = '<div class="foo"></div>'; let el = template.content.firstChild; 
  3. With DOMParser :

     let el = (new DOMParser()) .parseFromString('<div class="foo"></div>', 'text/html') .body.childNodes[0]; 

All of the above create the element correctly, the node is inserted into the DOM but the editor library won't start.

With jQuery, the element is inserted and the editor library starts:

    let el = $('<div class="foo"></div>')

To sum things up, I'm not looking for advice on implementing the Trix library but I'd like to know what jQuery does different when it creates an element.

Basically, jQuery uses RegExp and other tricks to parse the relevant parts from the string. For the example you gave, it would get an element of type div with a class attribute that has a value of foo .

Then it uses that data to create the element and add the properties corresponding to the attributes:

var element = document.createElement("div");
element.className = "foo"; // className is the DOM property equivalent to the class attribute

And that's it for this particular example, since the element doesn't have any child elements indicated by the HTML string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM