← Back to Chapters

jQuery Add Elements

➕ jQuery Add Elements

? Quick Overview

jQuery provides multiple methods to dynamically add new elements to the DOM. These methods allow inserting content inside or around existing elements in real time.

? Key Concepts

  • append() adds content at the end
  • prepend() adds content at the beginning
  • before() inserts content before an element
  • after() inserts content after an element

? Interactive Playground

#target-element

(Inside the box)

? Syntax / Theory

? View Code Example
// General syntax for adding elements using jQuery
$(selector).append(content);
$(selector).prepend(content);
$(selector).before(content);
$(selector).after(content);

? Code Example

? View Code Example
// Buttons dynamically insert elements relative to #demo
$("#demo").append("<p>Appended</p>");
$("#demo").prepend("<p>Prepended</p>");
$("#demo p:first").before("<p>Before</p>");
$("#demo p:first").after("<p>After</p>");

? Live Output / Explanation

This is a paragraph.

Explanation

Each button inserts a new paragraph at a different position relative to the selected elements using jQuery DOM manipulation methods.

? Additional Example: appendTo()

? View Code Example
// appendTo() adds an element into the target container
$("<p>Appended using appendTo</p>").appendTo("#appendToExample");

Target container:

? Use Cases

  • Adding items to lists dynamically
  • Creating alerts or notifications
  • Building interactive UI components
  • Rendering data fetched from APIs

✅ Tips & Best Practices

  • Prefer append/prepend for content inside containers
  • Avoid duplicate IDs when adding elements
  • Ensure the DOM is loaded before manipulation

? Try It Yourself

  • Insert a paragraph after a heading using after()
  • Add a badge before a list item using prepend()
  • Create a button that appends list items dynamically