Languages
[Edit]
EN

JavaScript - how to create dynamically html element?

7 points
Created by:
Kate_C
19790

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.
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join