How to Add a Div to an Element Horizontally Using JavaScript

Today, we’re tackling a question that trips up many developers: “How do I add elements horizontally using JavaScript?” The short answer? Yes, you can! But it’s not just about JavaScript it’s a teamwork exercise between your code and CSS. Let’s break down a practical example, fix common misconceptions, and add some nifty features to make your UI shine.

Adding Elements Side by Side

Let’s start with the basics. The goal is to dynamically add elements (like dropdowns or buttons) to a form and arrange them horizontally. Here’s how the original code works:

HTML & CSS Setup

  • Container: A <form id="filter"> holds all elements.
  • CSS Styling: The .inline-element class uses display: inline-block to force horizontal alignment.
<style>
  .inline-element {
    display: inline-block; /* Magic for horizontal layout! */
    margin-right: 10px;    /* Adds spacing between elements */
  }
</style>
<form id="filter"></form>

Run HTML

Creating and Appending Elements

  1. Text Node: A label (“Choose Field:”) is added to the form.
  2. Dropdowns: Two <select> elements are created, styled with .inline-element, and appended to the form.
  3. Options: Options are dynamically added to the dropdowns.
// Create dropdowns
const selectFields = document.createElement('select');
selectFields.className = 'inline-element';
filter.appendChild(selectFields);

// Add options
const option1 = document.createElement('option');
option1.text = 'Field 1';
selectFields.appendChild(option1);

Key Insight:

  • appendChild() adds elements vertically by default.
  • CSS (display: inline-block) overrides this, arranging them horizontally.

Common Pitfall: Layout vs. Insertion Order

A big “aha!” moment here: JavaScript appends elements vertically by default. The horizontal arrangement is purely thanks to CSS. For example:

// These elements stack vertically without CSS...
filter.appendChild(selectFields);
filter.appendChild(selectOperators);

// ...but CSS transforms them into a row!

If you forget display: inline-block, your elements will stack like pancakes.

Enhanced Code: Extra Features for a Dynamic UI

Let’s level up the example with buttons to reset selections, add new options, and toggle visibility all while keeping everything horizontal!

“Show Selected” Button

Clicking this displays the selected values in a new <div>, styled to stay inline:

showButton.addEventListener('click', () => {
  const displayDiv = document.createElement('div');
  displayDiv.className = 'inline-element';
  displayDiv.textContent = `Selected: ${selectFields.value}`;
  filter.appendChild(displayDiv);
});

Reset Button

Clears selections and removes the result display:

resetButton.addEventListener('click', () => {
  selectFields.selectedIndex = 0; // Reset dropdown
  const displayDiv = document.getElementById('displayDiv');
  if (displayDiv) displayDiv.remove(); // Clean up
});

“Add New Option” Button

Dynamically inserts a new option into the first dropdown:

addOptionButton.addEventListener('click', () => {
  const newOption = document.createElement('option');
  newOption.text = `Field ${selectFields.options.length + 1}`;
  selectFields.appendChild(newOption);
});

Toggle Visibility Button

Hides/shows the dropdowns with a single click:

toggleButton.addEventListener('click', () => {
  const isHidden = selectFields.style.display === 'none';
  selectFields.style.display = isHidden ? 'inline-block' : 'none';
  selectOperators.style.display = isHidden ? 'inline-block' : 'none';
});

Why This Works

  • CSS Controls Layoutinline-block forces elements into a row.
  • JavaScript Manages Logic: Adding/removing elements dynamically.
  • Separation of Concerns: Keep styling in CSS and behavior in JavaScript.

Final Thoughts

Yes, you can add elements horizontally with JavaScript but it’s CSS that does the heavy lifting. The enhanced example shows how powerful this combo can be for building interactive UIs.

Next Steps:

  • Experiment with CSS Grid or Flexbox for more complex layouts.
  • Add animations when toggling visibility.
  • Let users drag-and-drop to reorder elements.

Related blog posts