Complete 2024 Web Development Bootcamp

Dr. Angela Yu

Back to jQuery Index Page


jQuery Elements
Adding & Removing
.before / .after

Adding new elements with jQuery is also pretty simple. Just decide whether you want your new element to be .before or .after an existing element. And then to actually add the new element, you write the code just as if you were writing innerHTML.

Let's say we have an <h1>This is an H1</h1> and we want to add a button element. The code would be something like:

  • $("h1").before("<button>New Button</button>");
would add a <button> before the <h1>, and
  • $("h1").after("<button>New Button</button>");
would add the <button> after the <h1> element. Notice that we are writing the code just like innerHTML and we're including the code for the new <button> and the button text.




.prepend / .append

We can also use .prepend and .append in the same way as .before and .after.

The difference here is that .before and .after will place the NEW element before or after the element that you have selected as a reference, but .prepend and .append will actually place the new element inside the current element.

In our example, we used an <h1> element and place a new button before, and after the actual <h1> element.

But with ,prepend and .append, it's going to actually place the new button, inside the <h1> elements itself with .prepend placing it at the beginning of the <h1> element, and .append placing it at the end of the <h1> element, but still within the <h1> element itself.

If we .prepend our <h1>, and inspect our code, we should see:

  • <h1><button>NewButton</button>"This is an H1"</h1>

and if we .append our <h1>, and inspect our code, we should see:

  • <h1>"This is an H1"<button>NewButton</button></h1>




.remove

We can also remove elements using the .remove method. In our previous example, if we wanted to remove our newly created <button>'s, we just write:

  • $("button").remove();
and this will remove all of our new buttons.

Now we have to bve careful here, because this will remove every button on the page, and we may only want to remove one. So we have to be careful in our element selection, and we may want to use a more specific selector.


Back to Top