JavaScript can dynamically create and place HTML elements side by side. This is useful for displaying lists, galleries, linked-list visualizations, and other horizontal layouts.
- Use CSS layout properties such as inline-grid or flex.
- Create elements dynamically with document.createElement().
- Append the elements to a common container.
Approach 1: Using display: inline-grid
The inline-grid property allows dynamically created elements to appear horizontally while maintaining their grid behavior.
<div id="division"></div>
<button onclick="insert()">Add Element</button>
<script>
let number = 1;
function insert() {
const div = document.createElement("div");
div.textContent = number;
div.style.display = "inline-grid";
div.style.margin = "5px";
document.getElementById("division").append(div);
number++;
}
</script>
- document.createElement() creates a new <div>.
- display: inline-grid places the elements horizontally.
- append() adds each new element to the container.
Approach 2: Using a <table>
A table row can be used when elements need to remain horizontally aligned in separate cells.
<table>
<tr id="tablerow"></tr>
</table>
<button onclick="insert()">Add Element</button>
<script>
let number = 1;
function insert() {
const td = document.createElement("td");
td.textContent = number;
td.style.padding = "10px";
document.getElementById("tablerow").append(td);
number++;
}
</script>
- Each element is created as a <td>.
- The <tr> keeps the elements in a horizontal row.
- This approach is useful for table-based layouts or visualizations.