Uploaded by xarowo2987

DOM - Tagged

advertisement
DOM
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 dynamically. The DOM
represents the document as a tree of nodes, where each
node corresponds to part of the page, such as an
element or an attribute.
• It basically catalogs the web page into individual objects
that we can select and manipulate.
Example
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1>Hello, World!</h1>
<p>This is a sample paragraph.</p>
</body>
</html>
Document
/
\
DOCTYPE
html
/
\
head
body
/
/
\
title
h1
p
|
|
|
"Sample Page" "Hello, World!" "This is a sample
paragraph."
Common methods to access html
elements using DOM
• document.firstElementChild
• document.lastElementChild
• var heading = document.lastElementChild.firstElementChild
• heading.innerHTML=“Good Bye”;
• heading.style.color=“red”;
• document.querySelector(“input”).click();
Select HTML elements with
Javascript
• document.getElementsByTagName(“li”);//returns the array
• document.getElementsByClassName(“btn”);//return the array
• document.getElementById(“title”);//returns single item
• document.querySelector(“h1”);
• document.querySelector(“#h1”);
• document.querySelector(“li a”);
• document.querySelector(“li.item”);
• document.querySelectorAll(“#list .item”);//returns the array
Manupulating Styles of HTML
Element
• It is similar to all the styles we can change with CSS.
• The only difference here is we cannot use - like “background-color”,
instead use the camelCase like backgroundColor.
Separation of Concern
• document.querySelector(“button”).classList.add(“invisible”);
• document.querySelector(“button”).classList.remove(“invisible”);
• document.querySelector(“button”).classList.toggle(“invisible”);
Text Manipulation
• Difference between innerHtml and textContent.
Download