0% found this document useful (0 votes)
58 views51 pages

JS-DOM-Events

The document discusses the Document Object Model (DOM) and how it allows JavaScript to access and manipulate HTML elements on a web page. It explains that the DOM represents the page as nodes and objects, which JavaScript can select and modify. Methods like getElementById(), getElementsByClassName(), and querySelector() allow selecting elements, while innerHTML, className, and style properties allow changing element content and styles. New elements can be created and added or removed from the page using createElement(), appendChild(), and removeChild().

Uploaded by

Nour H
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
58 views51 pages

JS-DOM-Events

The document discusses the Document Object Model (DOM) and how it allows JavaScript to access and manipulate HTML elements on a web page. It explains that the DOM represents the page as nodes and objects, which JavaScript can select and modify. Methods like getElementById(), getElementsByClassName(), and querySelector() allow selecting elements, while innerHTML, className, and style properties allow changing element content and styles. New elements can be created and added or removed from the page using createElement(), appendChild(), and removeChild().

Uploaded by

Nour H
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 51

MORE JAVASCRIPT

OBJECT
🞆An object is a thing or entity.
⚫ Browser window
⚫ Submit button
⚫ Web page document

2
DOCUMENT OBJECT MODEL
🞆 The backbone of an HTML document is tags.

🞆 According to the Document Object Model (DOM), every HTML tag is an


object. Nested tags are “children” of the enclosing one. The text inside a tag is
an object as well.

🞆 The DOM specification explains the structure of a document and provides


objects to manipulate it

🞆 When a web page is loaded, the browser creates a Document Object Model of
the page

🞆 DOM allows us to use JavaScript to control various aspects of our documents

🞆 The HTML DOM is a standard for how to get, change, add, or delete
HTML elements.
DOCUMENT OBJECT MODEL (DOM)
⚫ A portion of the DOM is
shown at the left.

⚫ Defines every object and


element on a web page

⚫ Hierarchical structure

⚫ Accesses page elements


and apply styles to page
elements
4
EXAMPLE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Example</title>
</head>
<body>
<p>Welcome To Java Script</p>
</body>
</html>

DOM viwer
http://software.hixie.ch/utilities/js/live-dom-viewer/dd text
5
WITH DOM YOU WILL LEARN HOW TO:
🞆How to access HTML elements through JavaScript

🞆How to change the content of HTML elements

🞆How to change the style (CSS) of HTML elements

🞆How to react to HTML DOM events

🞆How to add and delete HTML elements


READ/WRITE DOCUMENT ATTRIBUTES

🞆document.title
⚫ The title of the HTML document, usually the string that is
displayed in the browser’s window caption or tab bar

🞆document.body
⚫ Represents the body of the document
EXAMPLE

<head>
<title>My Document</title>
</head>
<body>
<script type = "text/JavaScript">
window.alert(document.title);
document.title = "Godzilla's Lair";
window.alert(document.title);
</script>
</body>
READ ONLY DOCUMENT ATTRIBUTES

🞆document.URL
⚫ A string that contains the full pathname of the currently open
HTML document

🞆document.lastModified
⚫ A string that contains the date for which the currently open
HTML document was last modified
DOM ACCESS
🞆 On every webpage, the document
object gives us ways of accessing and
changing the DOM.

🞆 Every DOM "node" has properties


that let us traverse the DOM like a
tree:
⚫ parentNode
⚫ childNodes
⚫ firstChild,
⚫ prevSibling,
⚫ nextSibling.
ACCESSING DOM NODES
🞆By id attribute value – returns an object
⚫ document.getElementById()
🞆By tag name – returns a collection (nodeList)
⚫ document.getElementsByTagName()
🞆By class attribute value – returns a collection (nodeList)
⚫ document.getElementsByClassName()
🞆By specifying the selector or group of selectors
⚫ document.querySelector()  returns first object matches the
selector criteria
⚫ document.querySelectorAll()  returns a collection (nodeList)
of all objects match the selector criteria
HTML ELEMENT
🞆Once we get an element using the function
document.getElementById, we can
⚫ Change the content (innerHTML) of the element
⚫ Change the attributes of the element
🞆Change the CSS class name of the element
🞆Change the CSS of the element
🞆And much more
EXAMPLE

<html>
<head>
<title>My Document</title>
</head>
<body>

<p id= " foundation" >Founded in 1991, PSUT is the only private and non-
profit university in Jordan. </p>
<p class= " psut" >Being part of El Hassan Science City, PSUT strives to
create a culture of entrepreneurship among its students.</p>
<p class= " psut" >PSUT encourages creativity and innovation in all areas
of life. </p>

</body>
</html>
GETELEMENTBYID()

<script>
var parag= document.getElementById(“foundation");

document.write(parag.innerHTML);

</script>
GETELEMENTSBYCLASSNAME()

<script>
var paragraphs = document.getElementsByClassName("psut");

for( var i = 0; i < paragraphs.length; i++ ) {


document.write(paragraphs[i].innerHTML);
document.write("<br>"); }

</script>
GETELEMENTSBYTAGNAME()

🞆Gets an array of all elements of a stated tag type, which


you can access using Java-like array notation
GETELEMENTSBYTAGNAME()
<body>
<p>Learned discussion of Marcel Proust here</p>
<p>Biography of Cicero here</p>
<script>
var paragraphs =
document.getElementsByTagName("p");

paragraphs[0].innerHTML = "Godzilla was taller";


paragraphs[1].innerHTML = "Bruce Lee was a better actor";
</script>
</body>
DOCUMENT.QUERYSELECTOR()
HTML
<h3>vehicle category </h3>
<ol>
<li>Bicycle</li>
<li>Motorcycle</li>
<li>Car</li>
<li>Bus</li>
</ol>

JS
let myVehicle = document.querySelector(“ol li");
alert(myVehicle.innerHTML); // will alert with Bicycle
DOCUMENT.QUERYSELECTOR()
HTML
<h3>vehicle category </h3>
<ol>
<li>Bicycle</li>
<li>Motorcycle</li>
<li>Car</li>
<li>Bus</li>
</ol>

JS
let allVehicles = document.querySelectorAll(“ol li");
for( i=0; i< allVehicles.length; i++)
documrnt.write(allVehicles[i].innerHTML + “<br>”); // will output: Bicycle
Motorcycle
Car
Bus
HTML ELEMENT ATTRIBUTES
🞆All HTML objects have the following attributes, for
which you can change using the HTML DOM
⚫ id
⚫ className
⚫ title
⚫ innerHTML
🞆Inner HTML is the content between the start and end tags of an
HTML element
ACCESSING AN ATTRIBUTE VALUE
🞆getAttribute()

🞆setAttribute()

🞆innerHTML

🞆style
GETATTRIBUTE()

HTML
<img src="stratocaster.jpg" alt="electric guitar" id="lead-image">

JS

var bigImage = document.getElementById("lead-image");


alert( bigImage.getAttribute("src") ); // Alerts "stratocaster.jpg“
SETATTRIBUTE()

HTML
<img src="stratocaster.jpg" alt="electric guitar" id="lead-image">

JS

var bigImage = document.getElementById("lead-image");


bigImage.setAttribute("src", "lespaul.jpg");
HOW TO CHANGE INNER HTML
🞆Create an HTML element, say a p element with some
content in it
🞆Assign an ID to the element
🞆Get a handle to the HTML element using the
document.getElementByID(ID) function
🞆Assign new content using handle.innerHTML
⚫ The innerHTML in this case is a string that can even contain
HTML code in it!
DOM INNERHTML
🞆 The easiest way to get the content of an element is by using
the innerHTML property.
🞆 Each DOM node has an innerHTML property with the HTML of
all its children:
🞆 The innerHTML property is useful for getting or replacing the
content of HTML elements.
EXAMPLE: INNERHTML

HTML
<div class=“intro">First Div</div>
<div class=“intro">Second Div</div>
<div class=“intro"><p>Third Div<p></div>

JS

var introDiv = document.getElementsByClassName("intro");


introDiv[0].innerHTML = "<p>This is our intro text</p>";
introDiv[2].innerHTML = "<h1>This is our intro text<h1></p>";
STYLE

HTML
<div id=“myintro">Intro Div</div>

JS

document.getElementById(“myintro").style.color = "#fff";
document.getElementById(“myintro").style.backgroundColor = "#f58220";

NOT
background-color
as in CSS
CHANGE CSS CLASS USING
GETELEMENTBYID
document.getElementById("myElemnt").className =
"myStyle";

Example:
HTML:
<p id=“intro” class = “basic”>Sample Text</p>
CSS:
.basic{ }
.advanced{}

JavaScript:
document.getElementById(“intro").className = “advanced";
COUNT HOW MANY CHECKBOXES CHECKED
HTML

<form id="vehicleGroup">
<input type="checkbox" name="vehicles" value="car“ /> Car
<input type="checkbox" name="vehicles" value="truck“ /> truck
<input type="checkbox" name="vehicles" value="bike“ /> bike
</form>

JS
var numchecked = 0;
var dom=document.getElementById("vehiclegroup");

for (index=0,index<dom.vehicles.length;index++)
if (dom.vehicles[index].checked)
numchecked++;

alert(numchecked);
ADDING AND REMOVING ELEMENTS
🞆createElement()

🞆createTextNode() =

🞆appendChild()

🞆insertBefore()

🞆replaceChild()

🞆removeChild()
CREATEELEMENT()
🞆enter text into either an element we’ve created or an
existing element on the page
HTML
<body>

</body>

JS

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


CREATETEXTNODE()
🞆 creates a DOM-friendly version of a string text, ready
for inclusion on the page.
HTML
<body>

</body>

JS

var ourText = document.createTextNode("This is our text.");


APPENDCHILD()
🞆Append (add) a DOM to an existing element that will be
its parent in the document structure
HTML
<body>
<div id="our-div"></div>
</body>

JS

var ourDiv = document.getElementById("our-div");


var newParagraph = document.createElement("p");
var copy = document.createTextNode("Hello, world!");

newParagraph.appendChild( copy );
ourDiv.appendChild( newParagraph );
INSERTBEFORE()
🞆inserts an element before another element

HTML
<body>
<div id="our-div">
<p id="our-paragraph">Our paragraph text</p>
</div>
</body>

JS
var ourDiv = document.getElementById("our-div");
var para = document.getElementById("our-paragraph");

var newHeading = document.createElement("h1");


var headingText = document.createTextNode("A new heading");
newHeading.appendChild( headingText );

ourDiv.insertBefore( newHeading, para );


REPLACECHILD()
🞆method replaces one node with another

HTML
<body>
<div id="our-div">
<div id="swap-me"></div>
</div>
</body>

JS
var ourDiv = document.getElementById("our-div");
var swapMe = document.getElementById("swap-me");

var newImg = document.createElement("img");


newImg.setAttribute( "src", “mypath/image.jpg" );

ourDiv.replaceChild( newImg, swapMe );


REMOVECHILD()
🞆removes a node or an entire branch from the document
tree
HTML
<div id="parent">
<div id="remove-me">
<p>Pssh, I never liked it here anyway.</p>
</div>
</div>

JS
var parentDiv = document.getElementById("parent");
var removeMe = document.getElementById("remove-me");

parentDiv.removeChild( removeMe );
JAVASCRIPT AND EVENTS
🞆JavaScript can be configured to perform actions
when events occur.
⚫ The event name is coded as an attribute of an HTML
tag
⚫ The value of the event attribute contains the JavaScript
code

Example:
Display an alert box when the mouse is placed over a
hyperlink.

<a href=“http://www.google.com" onmouseover="alert(‘Google’);">Google </a>


38
Events and events handlers

39
APPLYING EVENTS HANDLERS

🞆There are three common methods for applying


event handlers to items within our pages:
🞆As an HTML attribute
🞆As a method attached to the element
🞆Using addEventListener()

40
HANDLERS AS AN HTML ATTRIBUTE
HTML

<body onclick="myFunction();">
….
</body>

JS
function myFunction()
{
alert(“An element clicked");

}
HANDLERS AS A METHOD
HTML

<body>
….
</body>

JS
function myFunction()
{
alert(“An element clicked");

window.onclick = myFunction;
ADDEVENTLISTENER
HTML

<body >
….
</body>

JS
window.addEventListener("click", myFunction);

JS
// with an anonymous function

window.addEventListener("click", function(e) {
alert(“An element clicked");
});
EXAMPLE

<head>
<title>Demo</title>
<script lang = "javascript">
function thankuser() {
window.alert("thanks");
}
</script>
</head>
<body>
<button onclick = "thankuser();">
Click Me!
</button>
</body>
JAVASCRIPT TOOLKITS

🞆Many client-side scripting tasks can be done using JavaScript


libraries / toolkits
⚫ Save coding many common graphic elements
⚫ Best-known ones are JQuery and Dojo, both free
⚫ Google Web Toolkit contains both a JavaScript library and a Java-to-
JavaScript cross-compiler
🞆Code UI in Java using Swing-like code, automatically compile it into
JavaScript that can be placed in any web page.

45
NOTES FOR JAVASCRIPT DEBUGGING
⚫ Check the syntax of the statements
◦ Pay very close attention to upper and lower case letters, spaces,
and quotations

⚫ Verify that you have saved the page with your most recent
changes

⚫ Verify that you are testing the most recent version of the
page (refresh or reload the page)

⚫ Most browsers can display error messages:


◦ In Firefox: Select Tools / Error Console
◦ Chrome: Tools/Developer Tools
46
REMEMBER!
🞆JavaScript is case-sensitive
🞆Everything we have been doing this week and last is
case-sensitive
🞆If you misspell anything… you are doomed!
VIEW SOURCE AND JS

View Source will *not* show you the output


from execution of JavaScript, even with
document.write, which is executed at load
time.
JAVASCRIPT RESOURCES

🞆 JavaScript Tutorials
http://www.w3schools.com/JS

🞆 JavaScript Tutorial for the Total Non-Programmer


http://www.webteacher.com/javascript/

🞆 More Beginning JavaScript Tutorials


http://echoecho.com/javascript.htm

🞆 Core JavaScript 1.5 Reference Manual


http://www.webreference.com/javascript/reference/core_ref

🞆 Creating Accessible JavaScript


http://www.webaim.org/techniques/javascript

49
EXERCISE
<!DOCTYPE html>
<html>
<head> <meta charset="utf-8"/>
<title>About Me</title> </head>
<body>
<h1>About Me</h1>
<ul>
<li>Name: <span id="name"></span> </li> <li>Age: <span
id="age"></span> </li>
<li>Hometown: <span id="hometown"></span> </li>
</ul>
</body>
</html>
EXERCISE REQUIREMENT
🞆Add a script tag to the bottom.
🞆Change the body style so it has a font-family of "Arial,
sans-serif".
🞆Replace each of the spans (name, age, hometown) with
your own information.
🞆Iterate through each li and change the class to "listitem".
Add a style tag that sets a rule for "listitem" to make the
color red.
🞆Create a new img element and set its src attribute to a
picture of you. Append that element to the page.
SOLUTION
document.body.style.fontFamily = 'Arial, sans-serif';
document.getElementById('name').innerHTML = 'Pamela Fox';

document.getElementById('age').innerHTML = '27';
document.getElementById('hometown').innerHTML = 'Pasadena, CA';

var items = document.getElementsByTagName('li');


for (var i = 0; i < tems.length; i++) {
items[i].className = 'listitem';
}

var myPic = document.createElement('img');


myPic.src = 'http://gotocon.com/photos/speakers/Pamela_Fox.jpg';
document.body.appendChild(myPic);

You might also like