Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
31 views

11 - JavaScript DOM

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views

11 - JavaScript DOM

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

JavaScript DOM

by : Emmersive Learning

Join us :
Telegram : https://t.me/EmmersiveLearning

Youtube : https://www.youtube.com/@EmmersiveLearning/
Document Object Model.
The Document Object Model (DOM) is a programming interface for HTML and
XML documents. It represents the page so that programs can change the
document structure, style, and content. JavaScript can interact with the DOM to
manipulate web pages dynamically.
What is the DOM?

● The DOM treats an HTML document as a tree structure, where each


element is an object. You can access and manipulate these objects with
JavaScript.

For example, in the HTML code:

<html>
<body>
<h1>Hello, World!</h1>
<p>This is a paragraph.</p>
</body>
</html>

The DOM represents this as a tree:


html
├── body
├── h1
└── p

Using JavaScript, you can manipulate this structure to dynamically add, remove,
or modify content on the web page.

Accessing the DOM


The first step in manipulating the DOM is to select the elements you want to
work with. JavaScript provides several methods to access these elements:
1. getElementById()
○ Selects an element by its ID.

const element = document.getElementById('myId');

2. getElementsByClassName()
○ Selects all elements with a specific class name. Returns a collection
(array-like object).

const elements =
document.getElementsByClassName('myClass');

3. getElementsByTagName()
○ Selects all elements with a specific tag name (like div, p, h1, etc.).

const elements = document.getElementsByTagName('p');

4. querySelector()
○ Selects the first element that matches a CSS selector (like #id,
.class, tag).

const element = document.querySelector('#myId');

5. querySelectorAll()
○ Selects all elements that match a CSS selector. Returns a NodeList.
const elements = document.querySelectorAll('.myClass');

Manipulating the DOM

Once you've selected elements, you can manipulate them, such as changing
their content, style, or attributes.

1. Changing Content:
○ You can modify the inner HTML of an element using the
innerHTML property.

const element = document.getElementById('myId');


element.innerHTML = "New Content!";

2. Changing Styles:
○ You can update the CSS styles of an element using the style
property.

const element = document.querySelector('.myClass');


element.style.color = "red";
element.style.fontSize = "20px";

3. Changing Attributes:
○ You can modify the attributes of an element using the
setAttribute() method.

const element = document.querySelector('img');


element.setAttribute('src', 'newImage.jpg');

4. Adding and Removing Classes:


○ Use classList to add, remove, or toggle classes on elements.

const element = document.querySelector('.myClass');


element.classList.add('newClass');
element.classList.remove('oldClass');
element.classList.toggle('active');

Creating and Deleting Elements

1. Creating Elements:
○ You can create new HTML elements dynamically using the
createElement() method.
const newElement = document.createElement('p');
newElement.textContent = "This is a new paragraph.";
document.body.appendChild(newElement);

2. Removing Elements:
○ You can remove elements using the removeChild() or remove()
method.

const element = document.getElementById('myId');


element.remove();

Event Handling in the DOM

Events allow JavaScript to interact with user actions, such as clicking buttons,
typing, or hovering over elements. You can handle events using event listeners.

Adding an Event Listener:


Use addEventListener() to handle events like click, mouseover,
keydown, etc.

const button = document.querySelector('button');


button.addEventListener('click', function() {
alert('Button clicked!');
});
1. Removing an Event Listener:
You can also remove event listeners when they're no longer needed.

function showAlert() {
alert('Button clicked!');
}

const button = document.querySelector('button');


button.addEventListener('click', showAlert);

// Remove the event listener


button.removeEventListener('click', showAlert);

Traversing the DOM

You can navigate between elements using different DOM properties:


parentNode: Get the parent of an element.

const child = document.querySelector('p');


const parent = child.parentNode;

children: Get all child elements of a specific element.

const parent = document.querySelector('div');


const children = parent.children;
nextElementSibling and previousElementSibling: Navigate to the next
or previous sibling element.

const current = document.querySelector('p');


const next = current.nextElementSibling;
const prev = current.previousElementSibling;

firstElementChild and lastElementChild: Access the first and last child


of an element.

const parent = document.querySelector('ul');


const first = parent.firstElementChild;
const last = parent.lastElementChild.

Example: A Simple DOM Manipulation


<!DOCTYPE html>
<html>
<head>
<title>DOM Example</title>
</head>
<body>

<h1 id="heading">Welcome!</h1>
<button id="changeBtn">Change Heading</button>

<script>
const button = document.getElementById('changeBtn');

button.addEventListener('click', function() {
const heading = document.getElementById('heading');
heading.textContent = "Hello, JavaScript!";
heading.style.color = "blue";
});
</script>

</body>
</html>

In this example:

● When the button is clicked, the h1 element’s text and color are updated
using JavaScript.
Conclusion

JavaScript's interaction with the DOM allows developers to create dynamic and
interactive web pages. By understanding how to access and manipulate DOM
elements, handle events, and traverse the DOM tree, you can significantly
enhance user experiences on the web.

Would you like to try a DOM-based project, or dive deeper into any specific
aspect of the DOM?

DOP Properties and Methods List.

In JavaScript, the DOM (Document Object Model) provides a wide range of


properties and methods that allow you to interact with HTML and XML
documents. Here’s an overview of the most important DOM properties and
methods:

Common DOM Properties

1. document

● Represents the whole web page.


● Example: document.title gets or sets the title of the document.

2. document.body

● Refers to the <body> element of the HTML document.


● Example: document.body.innerHTML gets or sets the HTML inside the
body.

3. document.head

● Refers to the <head> section of the document.


● Example: document.head.querySelector('meta') selects the first
<meta> tag.

4. element.id

● Gets or sets the id of an element.


● Example: document.getElementById('myId').id = 'newId'.

5. element.className

● Gets or sets the class attribute of an element.


● Example: document.querySelector('div').className =
'newClass'.

6. element.classList

● Returns a DOMTokenList of the element’s classes.


● Example: element.classList.add('active').

7. element.tagName

● Returns the tag name of an element in uppercase.


● Example: document.querySelector('p').tagName would return
'P'.
8. element.innerHTML

● Gets or sets the HTML content inside an element.


● Example: document.getElementById('myDiv').innerHTML =
'<p>Hello World</p>'.

9. element.textContent

● Gets or sets the text content inside an element (ignores HTML tags).
● Example: document.querySelector('h1').textContent = 'New
Heading'.

10. element.style

● Allows you to manipulate the CSS styles of an element.


● Example: element.style.color = 'red'.

11. element.attributes

● Returns a NamedNodeMap of the attributes of an element.


● Example: element.attributes['class'].value would give the
value of the class attribute.

12. element.childNodes

● Returns a NodeList of all child nodes, including text and comment nodes.
● Example: element.childNodes[0] gives the first child node.

13. element.children
● Returns an HTMLCollection of child elements (only elements, no text or
comment nodes).
● Example: element.children[1] gives the second child element.

14. element.firstElementChild and element.lastElementChild

● Returns the first and last child element of a parent.


● Example: parent.firstElementChild gives the first child element.

15. element.parentNode

● Returns the parent node of the current element.


● Example: element.parentNode returns the parent element of element.

16. element.previousElementSibling and


element.nextElementSibling

● Returns the previous or next sibling element of the current element.


● Example: element.nextElementSibling returns the next sibling of
element.

17. element.innerHTML

● Gets or sets the HTML content inside an element.


● Example: element.innerHTML = "<p>New Content</p>".

18. element.nodeName and element.nodeType

● nodeName: The name of the node (e.g., DIV, P).


● nodeType: The type of node (1 = Element, 3 = Text, etc.).
● Example: element.nodeName might return DIV.
Common DOM Methods

1. getElementById()

● Selects an element by its id.


● Example: document.getElementById('myId').

2. getElementsByClassName()

● Selects all elements with a specific class name (returns an


HTMLCollection).
● Example: document.getElementsByClassName('myClass').

3. getElementsByTagName()

● Selects all elements with a specific tag name (returns an


HTMLCollection).
● Example: document.getElementsByTagName('div').

4. querySelector()

● Selects the first element that matches a CSS selector.


● Example: document.querySelector('div').

5. querySelectorAll()

● Selects all elements that match a CSS selector (returns a NodeList).


● Example: document.querySelectorAll('.myClass').

6. createElement()
● Creates a new HTML element.
● Example: const newElement =
document.createElement('div').

7. createTextNode()

● Creates a new text node.


● Example: const textNode = document.createTextNode('Hello
World').

8. appendChild()

● Appends a new child element or node to a parent element.


● Example: document.body.appendChild(newElement).

9. removeChild()

● Removes a child element from its parent.


● Example: parentElement.removeChild(childElement).

10. replaceChild()

● Replaces an existing child element with a new one.


● Example: parentElement.replaceChild(newElement,
oldElement).

11. setAttribute()

● Sets the value of an attribute on an element.


● Example: element.setAttribute('src', 'image.jpg').

12. getAttribute()
● Gets the value of an attribute.
● Example: element.getAttribute('href').

13. removeAttribute()

● Removes an attribute from an element.


● Example: element.removeAttribute('class').

14. addEventListener()

● Attaches an event handler function to an element.

Example:

element.addEventListener('click', function() {
alert('Element clicked');
});

15. removeEventListener()

● Removes an event listener from an element.


● Example: element.removeEventListener('click',
handleClick).

16. cloneNode()

● Clones an element. You can optionally deep-clone it (including all child


elements).
● Example: const clone = element.cloneNode(true).

17. insertBefore()

● Inserts a new node before an existing node as a child of a specified parent.


● Example: parent.insertBefore(newElement,
existingElement).

18. scrollIntoView()

● Scrolls the element into view.


● Example: element.scrollIntoView().

19. focus()

● Focuses on an input element.


● Example: inputElement.focus().

20. blur()

● Removes focus from an input element.


● Example: inputElement.blur().

Node Properties and Methods

In addition to element-specific properties and methods, there are general Node


properties and methods that apply to all DOM nodes (elements, text nodes,
comments, etc.):

1. nodeName: Returns the name of the node (tag name for elements).
2. nodeType: Returns the type of the node (1 for elements, 3 for text nodes).
3. nodeValue: Gets or sets the value of a text node or attribute.
4. appendChild(): Adds a node as the last child of a parent.
5. removeChild(): Removes a child node from the DOM.
6. cloneNode(): Creates a copy of the node (shallow or deep).

Example: Using DOM Properties and Methods

Here’s a practical example to demonstrate some common DOM properties and


methods:

<!DOCTYPE html>
<html>
<head>
<title>DOM Manipulation Example</title>
</head>
<body>

<h1 id="mainHeading">Hello World!</h1>


<button id="changeText">Change Text</button>

<script>
// Select the button
const button = document.getElementById('changeText');

// Add event listener to the button


button.addEventListener('click', function() {
// Select the heading element
const heading = document.getElementById('mainHeading');

// Change its text content


heading.textContent = 'JavaScript is awesome!';

// Change its style


heading.style.color = 'blue';
heading.style.fontSize = '24px';
});
</script>

</body>
</html>

● This example shows how to select elements, modify their content, and
handle an event.

Happy Coding!
Mehammed Teshome

You might also like