EN
JavaScript - create dynamically html element
7
points
In JavaScript, it is possible to create elements dynamically in the following ways.
1. document.createElement
method example
With this approach, it is possible to create elements 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:
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: