DOM Elements API

$.create()

Creates an HTML element in the document using the specified tag name and options.

  • Accepts the tag name of the element as a string as its first argument.
    Accepts an optional second argument, which is an object with the following properties:
    Property
    Type
    Description
    attr
    object
    An object with keys as attribute names and values as the corresponding attribute values.
    txt
    string
    A string that defines the text content inside the created element.
    Has precedence over the "html" property.
    html
    string
    A string that defines the HTML content inside the created element.
    children
    array
    An array of HTML elements to be inserted into the created element.
    All properties are optional.
  • Returns the created HTML element.
Example:
$.create();
// false

$.create('div');
// <div></div>

$.create('button', {
   attr: {type: 'button', id: 'myButton', class: 'btn', 'data-click': 'myComponent'},
   txt: 'Click me'
});
// <button type="button" id="myButton" class="btn" data-click="myComponent">Click me</button>

$.create('div', {
   attr: {id: 'container', class: 'container'},
   children: [
      $.create('p', {html: '<span>HTML content</span>'}),
      $.create('a', {attr: {href: '#', class: 'link'}, txt: 'Link'}),
      $.create('ul', {
         attr: {class: 'list'},
         children: [
            $.create('li', {txt: 'First'}),
            $.create('li', {txt: 'Second'}),
            $.create('li', {txt: 'Third'})
         ]
      })
   ]
});
/*
   <div id="container" class="container">
      <p><span>HTML content</span></p>
      <a href="#" class="link">Link</a>
      <ul class="list">
         <li>First</li>
         <li>Second</li>
         <li>Third</li>
      </ul>
   </div>
*/