Top community members
All Wiki Articles Create Wiki Article

Many years me and my friends we were volunteers on my university doing programming classes for young people.

I got main conclusion: Young people are awesome, especially students, because they always bring new and fresh ideas :)
* I loved to do it but my time is limited

  I decided to create something that will help millions of students

Now I am here

co-founder

JavaScript - how to create dynamically html element?

0 contributions
7 points

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.
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more