Trivia Questions1 min readPremium

How can you add a span element inside a div element using web APIs?

Adding a Span Element to a Div Using Web APIs

In web development, dynamically modifying the Document Object Model (DOM) is a common task. One such example is adding a <span> element inside a <div> element using JavaScript. Here’s a step-by-step guide to achieve this using web APIs. The same approach works whenever you need to add an element to the DOM; see MDN’s appendChild() reference.

How to Add an Element to the DOM: Step by Step

  1. Select the Div Element: Use methods like getElementById, getElementsByClassName, or querySelector to select the target <div> element.
  2. Create a Span Element: Use document.createElement('span') to create a new <span> element.
  3. Configure the Span: Optionally, set attributes, styles, or content for the <span> using properties like className, id, or textContent.
  4. Insert the Span into the Div: Use the appendChild method on the <div> to add the <span> as its child.

Example Code

// Select the div element
const divElement = document.getElementById('myDiv');

// Create a new span element
const spanElement = document.createElement('span');

// Set the text content of the span
spanElement.textContent = 'This is a span element';

// Add a class to the span for styling
spanElement.className = 'highlight';

// Append the span... premium content.
Premium

Keep reading with Premium

Get the rest of this guide plus every premium question, solution, and system design deep dive.

  • All premium solutions
  • System design deep dives
  • Company-specific prep

4.9/5 from our users