Module 6 - Lesson 10

Inserting, Replacing and Removing Elements

In this lesson, I’ll show you how you can control the DOM and change whatever you want inside your website structure.

We’ll get familiar with various methods for adding new content inside elements: append(), prepend(), appendTo() and perpendTo(). We’ll go over adding new content as sibling element using before(), after(). We’ll learn how to replace elements with replaceWith() and replaceAll() methods. I will explain the differences between remove(), detach() and empty() for removing content from a page.

Video Chapters

00:00 Introduction

00:49 append()

01:54 appendTo()

03:30 prepend()

04:15 prependTo()

05:10 before() and after()

09:57 replaceWith()

12:34 replaceAll()

13:30 remove()

14:29 detach()

16:46 empty()

Add element as a last child

$('ul ul').append('
  • this is last
  • '); $('
  • this is last
  • ').appendTo('ul ul');

    Add element as a first child

    $('ul ul').prepend('
  • this is first
  • '); $('
  • this is first
  • ').prependTo('ul ul');

    Add element as a sibling, before the target

    $('.green-box').before('
    Second green
    ');

    Add element as a sibling, after the target

    $('.green-box').after('
    Second blue
    '); $('p').after($('.orange-box'));

    Replace elements

    $('ul').replaceWith($('.blue-box'));
    $('ul').replaceWith('

    hello

    '); $('

    hello

    ').replaceAll($('ul'));

    Remove elements

    $('#element').remove();

    Detach elements

    $('#element').remove();
    
    var detachedList = $('ul.main').detach();
    $('#main-content').append(detachedList);

    Remove everything from the element, but not the element itself

    $('p').empty();

    Join the discussion

    Share your thoughts about this lesson with fellow students!

    Login to your Account

    If you're a DSA Student, please log in to your account to access the course content.

    Sorry, you don't have access to this content.

    It looks like you're not enrolled in Divi Stylist Academy.