0% found this document useful (0 votes)
6 views

The DOM Level 2 and level 3

The document provides an overview of manipulating the DOM using JavaScript, covering topics such as adding, removing, and replacing elements, as well as working with XML namespaces and styles. It also discusses accessing element dimensions, traversing the DOM, and using NodeIterator and TreeWalker for node navigation. Additionally, it explains the concept of Ranges for selecting and manipulating fragments of the DOM, including differences in handling Ranges in modern browsers versus older versions of Internet Explorer.

Uploaded by

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

The DOM Level 2 and level 3

The document provides an overview of manipulating the DOM using JavaScript, covering topics such as adding, removing, and replacing elements, as well as working with XML namespaces and styles. It also discusses accessing element dimensions, traversing the DOM, and using NodeIterator and TreeWalker for node navigation. Additionally, it explains the concept of Ranges for selecting and manipulating fragments of the DOM, including differences in handling Ranges in modern browsers versus older versions of Internet Explorer.

Uploaded by

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

1.

DOM Changes

The DOM (Document Object Model) represents a webpage as a tree of nodes (elements, text,
etc.). "DOM Changes" refers to modifying this tree dynamically using JavaScript.

 Adding Elements:
o Use createElement() to make a new element, then attach it with
appendChild(), prepend(), or insertBefore().

// Example: Add a paragraph

let newP = document.createElement("p");

newP.textContent = "This is a new paragraph!";

document.body.appendChild(newP); // Adds to end of body

// Example: Insert before an existing element

let existingDiv = document.querySelector("div");

let newSpan = document.createElement("span");

newSpan.textContent = "Inserted before div!";

document.body.insertBefore(newSpan, existingDiv);

 Removing Elements:
o Use removeChild() (older) or remove() (modern).

// Example: Remove a paragraph

let pToRemove = document.querySelector("p");

pToRemove.parentNode.removeChild(pToRemove); // Old way

// Modern way

let anotherP = document.querySelector("p");

anotherP.remove();

 Replacing Elements:
o Use replaceChild() to swap one node for another.

// Example: Replace a div with a new one

let oldDiv = document.querySelector("div");

let newDiv = document.createElement("div");

newDiv.textContent = "Replacement div!";

document.body.replaceChild(newDiv, oldDiv);

2. XML Namespaces

XML Namespaces prevent naming conflicts in XML-based documents (e.g., XHTML, SVG)
by associating elements/attributes with a unique identifier (namespace URI).

 Syntax in XML:

<svg xmlns="http://www.w3.org/2000/svg">

<rect width="100" height="100"/>

</svg>

 In JavaScript:
o Use createElementNS() to create elements with a namespace.
o Use getElementsByTagNameNS() or setAttributeNS() for namespace-aware
operations.

// Example: Create an SVG element

let svgNS = "http://www.w3.org/2000/svg";

let svg = document.createElementNS(svgNS, "svg");

svg.setAttributeNS(null, "width", "200");

svg.setAttributeNS(null, "height", "200");

let rect = document.createElementNS(svgNS, "rect");


rect.setAttributeNS(null, "x", "10");

rect.setAttributeNS(null, "y", "10");

rect.setAttributeNS(null, "width", "50");

rect.setAttributeNS(null, "height", "50");

rect.setAttributeNS(null, "fill", "blue");

svg.appendChild(rect);

document.body.appendChild(svg);

// Result: A blue 50x50 rectangle inside a 200x200 SVG

 Accessing Namespaced Elements:

let svgs = document.getElementsByTagNameNS(svgNS, "svg");

console.log(svgs[0]); // Logs the SVG element

wrapped in a div

3. Other Changes

This covers additional DOM modifications beyond basic additions/removals.

 Changing Attributes:

let img = document.createElement("img");

img.setAttribute("src", "example.jpg");

img.setAttribute("alt", "Example Image");

document.body.appendChild(img);

// Or directly:

img.src = "newimage.jpg";
 Modifying Text:

let p = document.createElement("p");

p.textContent = "Original text";

document.body.appendChild(p);

p.textContent = "Updated text"; // Overwrites

 Inner HTML:

let div = document.createElement("div");

div.innerHTML = "<p>Nested <strong>bold</strong> text</p>";

document.body.appendChild(div);

 Classes:

let span = document.createElement("span");

span.textContent = "Styled text";

span.classList.add("highlight", "bold");

document.body.appendChild(span);

// CSS: .highlight { color: yellow; } .bold { font-weight: bold; }

4. Styles

Styles define an element’s appearance, manipulated via the style property.

 Setting Inline Styles:

let div = document.createElement("div");

div.textContent = "Styled div";

div.style.backgroundColor = "lightblue";

div.style.padding = "10px";
div.style.fontFamily = "Arial";

document.body.appendChild(div);

 Multiple Styles:

let p = document.createElement("p");

p.textContent = "Fancy text";

Object.assign(p.style, {

color: "green",

fontSize: "20px",

border: "1px solid black"

});

document.body.appendChild(p);

5. Accessing Element Styles

Read or modify styles dynamically.

 Inline Styles:

let div = document.createElement("div");

div.style.color = "red";

console.log(div.style.color); // "red"

document.body.appendChild(div);

 Computed Styles:
o Use getComputedStyle() for all applied styles (inline + stylesheets).

// CSS: div { font-size: 16px; }

let div = document.querySelector("div");


let styles = window.getComputedStyle(div);

console.log(styles.fontSize); // "16px"

console.log(styles.getPropertyValue("font-size")); // "16px"

6. Working with Style Sheets

Manipulate CSS rules in <style> or <link> elements via document.styleSheets.

 Accessing Stylesheets:

// HTML: <style>p { color: blue; }</style>

let sheet = document.styleSheets[0];

console.log(sheet.cssRules[0].cssText); // "p { color: blue; }"

 Adding Rules:

let style = document.createElement("style");

document.head.appendChild(style);

let sheet = style.sheet;

sheet.insertRule("h1 { font-size: 24px; }", 0);

 Modifying Rules:

sheet.cssRules[0].style.fontSize = "30px";

 Removing Rules:

sheet.deleteRule(0);

7. Element Dimensions

Get or set an element’s size and position.

 Basic Dimensions:
o offsetWidth/offsetHeight: Includes borders.
o clientWidth/clientHeight: Excludes borders, includes padding.

let div = document.createElement("div");

div.style.width = "100px";

div.style.height = "100px";

div.style.border = "5px solid black";

document.body.appendChild(div);

console.log(div.offsetWidth); // 110 (100 + 5 + 5)

console.log(div.clientWidth); // 100

 Position:
o offsetTop/offsetLeft: Relative to offset parent.
o getBoundingClientRect(): Relative to viewport.

console.log(div.offsetTop); // Distance from top of parent

let rect = div.getBoundingClientRect();

console.log(rect.top, rect.left); // Position in viewport

8. Traversals

Navigate the DOM tree using node relationships.

 Basic Traversal:

// HTML: <div><p>Text</p><span>Span</span></div>

let div = document.querySelector("div");

console.log(div.parentNode); // <body>

console.log(div.children); // [<p>, <span>]

console.log(div.firstChild); // <p> (or text node if whitespace)

console.log(div.nextSibling); // null or next node


 Modern Traversal:

let p = div.querySelector("p");

console.log(p.nextElementSibling); // <span> (ignores text nodes)

9. NodeIterator

Iterates over DOM nodes sequentially with filtering.

 Basic Usage:

// HTML: <body><p>One</p><span>Two</span></body>

let iterator = document.createNodeIterator(

document.body,

Node.ELEMENT_NODE // Only elements

);

let node;

while ((node = iterator.nextNode())) {

console.log(node.tagName); // "P", "SPAN"

 With Filter:

let filter = {

acceptNode: (node) => (node.tagName === "P" ? Node.FILTER_ACCEPT :


Node.FILTER_SKIP)

};

let iterator = document.createNodeIterator(document.body,


Node.ELEMENT_NODE, filter);
while ((node = iterator.nextNode())) {

console.log(node.textContent); // "One" (only <p>)

10. TreeWalker

Like NodeIterator, but bidirectional and hierarchical.

 Basic Usage:

// HTML: <body><div><p>One</p><span>Two</span></div></body>

let walker = document.createTreeWalker(document.body,


Node.ELEMENT_NODE);

console.log(walker.nextNode().tagName); // "DIV"

console.log(walker.nextNode().tagName); // "P"

console.log(walker.nextNode().tagName); // "SPAN"

console.log(walker.previousNode().tagName); // "P"

 With Filter:

let filter = { acceptNode: (node) => (node.tagName === "SPAN" ?


Node.FILTER_ACCEPT : Node.FILTER_SKIP) };

let walker = document.createTreeWalker(document.body,


Node.ELEMENT_NODE, filter);

console.log(walker.nextNode().textContent); // "Two"

11. Ranges

A Range represents a fragment of the DOM (e.g., a selection of text or nodes).

 Creating and Setting:


// HTML: <body><p>Hello, world!</p></body>

let range = document.createRange();

let p = document.querySelector("p");

range.selectNodeContents(p); // Selects "Hello, world!"

 Manipulating:

range.deleteContents(); // Removes "Hello, world!"

range.insertNode(document.createTextNode("New content"));

// Result: <p>New content</p>

 Partial Selection:

let range = document.createRange();

let textNode = p.firstChild;

range.setStart(textNode, 0);

range.setEnd(textNode, 5);

console.log(range.toString()); // "Hello"

12. Ranges in the DOM

Standard DOM Ranges (W3C spec) are supported in modern browsers.

 Advanced Usage:

// HTML: <body><div><p>First</p><p>Second</p></div></body>

let range = document.createRange();

let div = document.querySelector("div");

range.setStartBefore(div.firstChild); // Before <p>First</p>


range.setEndAfter(div.lastChild); // After <p>Second</p>

let fragment = range.extractContents(); // Removes and returns


<p>First</p><p>Second</p>

document.body.appendChild(fragment);

// Result: <body><div></div><p>First</p><p>Second</p></body>

 Cloning:

let clone = range.cloneContents(); // Copies without removing

document.body.appendChild(clone);

13. Ranges in Internet Explorer

Older IE (pre-Edge) used TextRange, not the W3C Range API.

 Basic Usage:

// HTML: <body><p>Test text</p></body>

let textRange = document.body.createTextRange();

textRange.moveToElementText(document.querySelector("p"));

textRange.text = "New text"; // Replaces content

textRange.select(); // Highlights it

 Positioning:

textRange.moveStart("character", 2); // Move start 2 chars

textRange.moveEnd("character", -2); // Move end back 2 chars

console.log(textRange.text); // Substring of text

Note: TextRange is obsolete. Modern browsers (including Edge) use the standard Range API,
so focus on that unless supporting IE < 11.

You might also like