Basic DOM Manipulation

1. Introduction

In this tutorial, we will be learning about the various different ways in which we can manipulate the HTML DOM using jQuery.

2. DOM Manipulation

2.1 Get Content

To retrieve content from the DOM, there are three basic methods provided by jQuery –

  • text() – Gets the text content of the selected element
  • html() – Gets the content of the selected element including the HTML markup
  • val() – Used with forms, to get the value of form fields
  • attr() – Gets the attribute value of an element

2.1.1 Example Code


2.2 Set contents

The same above methods can be used to set content into the DOM –

  • text() – Sets the text content of the selected element
  • html() – Sets the content of the selected element including the HTML markup
  • val() – Used with forms, to set the value of form fields
  • attr() – Gets the attribute value of an element

2.2.1 Example Code

2.3 Add content to existing DOM

To add content to the DOM, following basic methods are provided by jQuery –

  • append() – add content just before the end of the selected element
  • prepend() – add content just after the beginning of the selected element
  • after() – add content after the selected element
  • before() – add content before the selected element

2.3.1 Example Code

2.4 Remove HTML DOM elements

To remove elements from the DOM, following methods are provided by jQuery –

  • remove() – Removes the selected element along with its child elements
  • empty() – Removes all the child elements from the selected element

2.4.1 Example Code

Receive our updates to your inbox

Get more stuff like this
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.