Languages
[Edit]
EN

JavaScript - how to create dynamically html element?

7 points
Created by:
Kate_C
2857

In JavaScript it is possible to create element dynamically in following ways.

1. document.createElement method example

With this approach it is possible to create element with pure JavaScript (VanillaJS).

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
  <style>
  
  .red-box {
    border: 1px solid red;
  }

  </style>
  <script>
  
    var element = document.createElement('div');

    element.className = 'red-box';
    element.innerText = 'This is internal text...';

    document.body.appendChild(element);

  </script>
</body>
</html>

Result:

Dynamically created div element - browser preview.
Dynamically created div element - browser preview.
Dynamically created div element - Google Chrome development tools preview.
Dynamically created div element - Google Chrome development tools preview.

2. Create new element operation with jQuery example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  </head>
<body>
  <style>
  
  .red-box {
    border: 1px solid red;
  }

  </style>
  <script>

    $(document).ready(function() {
      var element = $('<div class="red-box">This is internal text...</div>');
      
      $(document.body).append(element);
    });
    
  </script>
</body>
</html>

Notes:

  • $(document).ready(function() {...}); - runs code when web page is ready (this approach is necessary when jQuery is used),
  • $('<div ...>...</div>'); - creates new div element described by pure html,
  • $(document.body).append(element); - wraps body element with jquery logic and appends created element to body.

Result:

Dynamically created div element with jQuery - browser preview.
Dynamically created div element with jQuery - browser preview.
Dynamically created div element with jQuery - Google Chrome development tools preview.
Dynamically created div element with jQuery - Google Chrome development tools preview.
Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.