offline version v3


168 of 264 menu

createElement method

The createElement method allows you to create a new element by passing a tag name as a parameter. Once created, the element can be manipulated like a normal element, and it can also be added to a page using the prepend, append, appendChild, insertBefore or insertAdjacentElement methods.

If we write the result of createElement into a variable, then this variable will contain such an element as if we got it through querySelector or getElementById. The only difference is that our element will not be placed on the page. And so we can change its innerHTML, attributes, hang event handlers and finally place it on the page.

Syntax

document.createElement('tag name');

Example

Let's create a paragraph, set its text and place it on a page at the end of the #parent block:

<div id="parent"> <p>1</p> <p>2</p> <p>3</p> </div> let parent = document.querySelector('#parent'); let p = document.createElement('p'); p.textContent = '!'; parent.appendChild(p);

The code execution result:

<div id="parent"> <p>1</p> <p>2</p> <p>3</p> <p>!</p> </div>

Example

ul is given. Let's place 9 li tags in it, while setting serial numbers as their text:

<ul id="parent"></ul> let parent = document.querySelector('#parent'); for (let i = 1; i <= 9; i++) { let li = document.createElement('li'); li.textContent = i; parent.appendChild(li); }

The code execution result:

<ul id="parent"> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> <li>8</li> <li>9</li> </ul>

Example

Let's attach event handlers to them when inserting elements:

<ul id="parent"></ul> let parent = document.querySelector('#parent'); for (let i = 1; i <= 9; i++) { let li = document.createElement('li'); li.textContent = i; li.addEventListener('click', function() { alert(this.textContent); }); parent.appendChild(li); };

:

See also

  • the cloneNode method
    that can be used to clone an element
  • the createTextNode method
    that can be used to create a new text node
enru