DOM Manipulation

DOM Basics

1. The Document Object Model (DOM) is a programming interface for web documents that represents the HTML or XML document as a tree structure, where each node represents an element, attribute, or piece of text in the document.

2. When a web page is loaded, the browser creates a DOM tree that represents the document's structure and content.

3. Each node in the tree is represented as js object, which we can access and manipulate using the DOM API.

4. Here, Html elements, comments, text, content, etc are refered as nodes of DOM tree.

DOM API

1. The DOM API (Application Programming Interface) is a set of programming interfaces and methods that allow developers to interact with the DOM tree and manipulate the content and structure of web documents.

2. The DOM API provides a standardized way to create, modify, and delete elements and attributes, change styles and classes, handle events, and more.

HTML Structure

Reference HTML structure:

<body>
  <h1>Falling In Love With Javascript</h1>
  <div class="container">
    <div class="item item1" id="itemone">1</div>
    <div class="item item2">2</div>
    <div class="item item3">3</div>
    <div id="itemfour" class="item item4">4</div>
    <div class="item item5">5</div>
  </div>
  <p>hello i'm paragraph</p>
</body>

Target Elements

1. getElementById('id_name')

2. getElementsByClassName('class_name')

3. getElementsByTagName('tag_name')

4. querySelector('css_selector')

5. querySelectorAll('css_selector')

Create and Insert Element

1. createElement('tag_name')

2. appendChild(element)

3. insertAdjacentElement('position',element)

Insert Text and Elements

1. textContent

2. innerHTML

Insert and Remove Attribute

1. setAttribute('attribute_name','value')

2. removeAttribute('attribute_name')

Traverse HTML Nodes

1. parentElement

2. nextElementSibling

3. previousElementSibling

4. children

5. childNodes

Remove HTML Element

1. remove()