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

JS Dom

The HTML DOM defines the logical structure of HTML documents and the way they are accessed and manipulated. It represents an HTML document as nodes and objects. The DOM methods getElementById, getElementsByTagName, getElementsByName allow selecting elements, while innerHTML, textContent, setAttribute help changing element attributes and content.

Uploaded by

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

JS Dom

The HTML DOM defines the logical structure of HTML documents and the way they are accessed and manipulated. It represents an HTML document as nodes and objects. The DOM methods getElementById, getElementsByTagName, getElementsByName allow selecting elements, while innerHTML, textContent, setAttribute help changing element attributes and content.

Uploaded by

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

HTML DOM

1
HTML DOM

HTML DOM

 Is an Object-Oriented model represent the


HTML document when it is loaded into a
web browser.

 Defines the logical structure of the


document and the way in which they can be
accessed.

 It defines:

 HTML elements as objects.

 Properties of all HTML elements.

 Methods to access all HTML elements.

2
HTML DOM

HTML DOM

3
JavaScript DOM Selectors

4
JavaScript DOM Selectors

To access HTML elements using the DOM, several methods are offered by
the object document:

 Selecting Elements by ID.

 Selecting Elements by Tag Name.

 Selecting Elements by Name.

 Selecting Elements by Class Name.

 Selecting Elements with CSS Selectors.

5
Selecting Elements by ID
Elements can be selected using their unique ID with the
“getElementById()” method. This is the easiest way to
find an HTML element in the DOM tree.

6
Selecting Elements by ID
getElementById()

Syntax
document.getElementById();

Example

<body>
Select
<p id="test1"> hello world </p>
<script>
var x=document.getElementById("test1");
</script>
</body>

7
Selecting Elements by Tag Name
Elements can be selected by their tag name using the
“getElementsByTagName()” method. This method
returns an array object of all child elements with the
given tag name.

8
Selecting Elements by Tag Name
getElementsByTagName()

Syntax
document.getElementsByTagName();

Example

<body>
Select
<div> hello world </div>
<div> Welcome to my class </div>
<script>
var x=document.getElementsByTagName("div");
</script></body>

9
Selecting Elements by Name
Selects all elements whose “name” attribute is equal to
the given argument using the “getElementsByName()”
method. this method returns an array of all child
elements with the given name.

10
Selecting Elements by Name
getElementsByName()

Syntax
document.getElementsByName();

Example

<body>
Select
<input type="text" name= "myInput">
<input type="text" name= "myInput">
<script>
var x=document.getElementsByName("myInput");
</script></body>

11
Selecting Elements by Class Name
The “getElementsByClassName()” method is used to
select all the elements having specific class names. This
method returns an array object of all child elements
which have all of the given class names

12
Selecting Elements by Class Name
getElementsByClassName()

Syntax
document.getElementsByClassName();

Example

<body>
Select
<h1 class= "xyz">NTI</h1>
<p class= "xyz">About NTI</p>
<script>
var x=document.getElementsByClassName("xyz");
</script></body>

13
Selecting Elements with CSS Selectors
The “querySelector()” and the “querySelectorAll()”
methods are used to select elements that matches the
specified CSS selector.

14
querySelector() method
Returns the first element (only) that matches the
specified CSS selector.

15
querySelectorAll() method
document.querySelector()

Syntax
document.querySelector();

Example

<body><div id="container">
Select
<p class="red"> Welcome to NTI </p>
<p class="red"> Hello World </p>
</div><script>
var x=document.querySelector("#container .red");
</script></body>

16
querySelectorAll() method
Returns an array of all the elements matches the
specified CSS selector.

17
querySelector() method
document.querySelectorAll()

Syntax
document.querySelectorAll();

Example

<body><div id="container">
Select
<p class="red"> Welcome to NTI </p>
<p class="red"> Hello World </p>
</div><script>
var x=document.querySelectorAll("#container .red");
</script></body>

18
Changing Elements Attributes

19
InnerHTML
The “innerHTML” is a property used to get or set the
HTML markup contained within the element.

20
Changing Elements Attributes
InnerHTML

Syntax
element.innerHTML;

Example

<body><div id="myDiv"><p>Welcome to NTI</p></div>


<script>
var div1=document.getElementById("myDiv");
div1.innerHTML="<h1>About NTI</h1>";
</script>
</body>

21
textContent
The “textContent” is a property used to get or set the
text contained within the element, without the HTML
tags.

22
Changing Elements Attributes
textContent

Syntax
element.textContent

Example

<body><div id="myDiv"><p>Welcome to NTI</p></div>


<script>
var div1 = document.getElementById("myDiv");
div1.textContent = "About NTI";
</script>
</body>

23
Changing Elements Attributes
Attributes

Syntax
element.attributeName

Example
<img src="myimg.jpg" alt="image 2" id="pic">
<script>
var x=document.getElementById("pic");
x.src = "car.jpg";
x.alt = "Javascript…";
x.width = "200";
x.height = "200";
x.id = "pic2";
</script></body>

24
Changing Elements Attributes
Attributes

Example: Using getElementsByTagName

<body><img src="car1.jpg"><img src="car2.jpg">


<script>
var x=document.getElementsByTagName("img");
document.write(x[0].src);
var y=document.getElementsByTagName("img").item(0);
document.write(y.src);
</script>
</body>

25
Changing Elements Attributes

 var x=document.getElementsByTagName("img");

Returns an array named (x) of all the “img” elements on the page,
to access it use: x[0], x[1]

 Ex: x[2].src="car1.jpg")

 To get the total number of images use “x.length”.

 var y=document.getElementsByTagName("img").item(0);

 var y=document.getElementsByTagName("img")[0];

Returns a variable named (y) of the first “img” element on the page,
to access it use: the variable “y” (ex: y.src="car1.jpg")

26
Changing Custom Attributes

27
setAttribute() method
Sets the value of an attribute for an element. If the
attribute already exists, the value is updated; otherwise
a new attribute is added with the specified name and
value.

28
Changing Custom Attributes
setAttribute()

Syntax
element.setAttribute(attrName,value)

Example

<p data-icon="arrow" id="p1"> some text </p>


<script>
var x = document.getElementById('p1')
x.setAttribute("data-icon","info");
</script>

29
getAttribute() method
Returns the value of a an attribute for the element. If
the given attribute does not exist, the value returned
will either be null or "" (the empty string)

30
Changing Custom Attributes
getAttribute()

Syntax
element.getAttribute(attrName)

Example

<p data-icon="arrow" id="p1"> some text </p>


<script>
var x = document.getElementById('p1')
var attr=x.getAttribute("data-icon");
console.log(attr) // arrow
</script>

31
removeAttribute() method
Removes the attribute with the specified name from the
element.

32
Remove Element’s Attribute
removeAttribute()

Syntax
element.removeAttribute(attrName)

Example

<p align="center" data-icon="arrow" id="p1"> some text </p>


<script>
var x = document.getElementById('p1')
x.removeAttribute("align");
x.removeAttribute("data-icon");
</script>

33
Changing the class of an HTML element

34
Changing the class of an HTML element

Syntax
document.getElementById("id").className="value";

Example

<body><p id="abc"> Welcome to NTI </p>


<script>
y = document.getElementById("abc");
y.className = "class1";
</script>
</body>

35
Changing the in-line style of an element

36
Changing the in-line style of an element

Syntax
document.getElementById("id").style.property="value";

Example

<body><p id="abc"> hello world </p>


<script>
y=document.getElementById("abc");
y.style.color="#000000";
y.style.marginTop="50px";
</script>
</body>

37
Adding a class to Element

38
Adding a class to Element

Syntax
document.getElementById("id").classList.add("className");

Example

<body><p id="test1" class="abc"> hello world </p>


<script>
y = document.getElementById("test1");
y.classList.add("xyz");
</script>
</body>

39
Removing a class from Element

40
Removing a class from Element

Syntax
document.getElementById("id").classList.remove("className");

Example

<body><p id="test1" class="xyz abc"> hello world </p>


<script>
y = document.getElementById("test1");
y.classList.remove("xyz");
</script>
</body>

41
Toggle a class for Element

42
Toggle a class for Element

Syntax
document.getElementById("id").classList.toggle("className");

Example

<body><p id="test1" class="xyz abc"> hello world </p>


<script>
y = document.getElementById("test1");
y.classList.toggle("xyz");
</script>
</body>

43
Child Creation

44
Child Creation
document.createElement()

 creates an Element Node with the specified name. this element is not
inserted by default to the page another methods like “.append()” and
“.prepend” is needed to place the created node on the document

Syntax

document.createElement("elementName");

Example

var x=document.createElement("li");

45
Child Creation
document.createElement()

Example: creating and adding new element as Last Child


<ul>
<li>Green</li>
<li>Orange</li>
<li>blue</li>
</ul>

<script>
var x = document.querySelector('ul');
var y = document.createElement("li");
// Creates a New li Element
y.innerHTML="Black";
// Adds contents for the new element
x.append(y);
// Attach the new li element to the selected ul parent
</script>
46
Child Creation
document.createElement()

Example: creating and adding new element as First Child


<ul>
<li>Green</li>
<li>Orange</li>
<li>blue</li>
</ul>

<script>
var x = document.querySelector('ul');
var y = document.createElement("li");
// Creates a New li Element
y.innerHTML="Black";
// Adds contents for the new element
x.prepend(y);
// Attach the new li element to the selected ul parent
</script>
47
Select Parent Element

48
Select Parent Element
.parentElement

 The “.parentElement” is read-only property returns the parent Element, or


null if the node either has no parent, or its parent isn't a DOM Element.

Syntax

element.parentElement;

Example

<ul>
<li>Green</li>
<li>blue</li>
</ul>
<script>
var x = document.querySelector('li');
x.parentElement.innerHTML="<li>black</li>";
</script>

49
Remove an Element

50
Remove an Element
.remove()

 Removes the object from the tree it belongs to.

Syntax

element.remove();

Example
<ul>
<li>Green</li>
<li>blue</li>
<li>red</li>
</ul>
<script>
var x = document.querySelector('li');
x.remove();
</script>

51
Events Handling

52
Events Handling

 HTML DOM events allow JavaScript to register different event handlers


on elements in an HTML document.

 Events are normally used in combination with functions, and the


function will not be executed before the event occurs (such as when a
user clicks a button).

 Every DOM element has its own “addEventListener()” method, which


allows you to listen specifically on that element.

53
Events Handling
addEventListener()

Syntax
element.addEventListener(event, function);

Example
<button>Click me</button>
<p>No handler here.</p>
<script>
var butt = document.querySelector("button");
butt.addEventListener("click", function() {
alert("Button clicked.");
});
</script></body>
54
Events Handling
addEventListener()

Example

<img src="abc.jpg">
<script>
var x = document.querySelector("img");
x.addEventListener("mousedown", function(x) {
if (x.which == 1) {alert("Left button");}
else if (x.which == 2) {alert("Middle button");}
else if (x.which == 3) {alert("Right button");}
});
</script>

55
Events Handling

Example: Direct Events Handling

<body>
<button>Click me</button>
<script>
var button1 = document.querySelector("button");
button1.onclick = function() {
alert("Button clicked.");
}
</script>
</body>

56
JavaScript Events

57
JavaScript Events

HTML DOM events allow JavaScript to register different event handlers on


elements in an HTML document.

 click

The event occurs when the user clicks on an element.

 change

The event occurs when the content of a form element, the selection,
or the checked state have changed (for <input>, <select>, and
<textarea>).

 Blur

The event occurs when an element loses focus.

58
JavaScript Events

 contextmenu

Occurs when the user right-clicks on an element to open a context


menu.

 copy

Occurs when the user copies the content of an element.

 cut

Occurs when the user cuts the content of an element.

 dblclick

Occurs when the user double-clicks on an element

59
JavaScript Events

 focus

Occurs when an element gets focus.

 keydown

Occurs when the user is pressing a key.

 keyup

Occurs when the user releases a key.

 keypress

Occurs when the user presses a key.

 mouseover

Occurs when the pointer is moved onto an element, or onto one of


its children
60
JavaScript Events

 mouseout

Occurs when a user moves the mouse pointer out of an element, or


out of one of its children.

 mouseup

occurs when a user releases a mouse button over an element

 mousedown

occurs when a user presses a mouse button over an element.

 paste

Occurs when a user pastes some content in an element.

61
JavaScript Events

 reset

Occurs when a form is reset.

 select

Occurs after the user selects some text (<input> <textarea>)

 submit

Occurs when a form is submitted.

 toggle

Occurs when a user toggle the <details> element.

 wheel

Occurs when the mouse wheel rolls up or down.

62
JavaScript Method Chaining
Method chaining is a technique that can be used to
simplify code in scenarios that involve calling multiple
functions on the same object .

63
JavaScript Method Chaining

Syntax
object.method().method().method();

Example
<input type="text">
<button onclick="demo()">Execute Script</button>
<script>
function demo() {
var x=document.querySelector("input");
y = x.value.trim().toUpperCase();
document.write(y);
}
</script>

64
Js Form Validation

65
Js Form Validation

JavaScript provides a way to validate form's data on the client's computer

before sending it to the web server. Form validation generally performs two

functions.

 Basic Validation: Firstly: the form must be checked to make sure all

the mandatory fields are filled in. It requires to loop through each

field in the form and check for data.

 Data Format Validation: Secondly, the data entered must be

checked for correct form and value.

66
Basic Form Validation
In the form invoke a function to validate data when the
form submit event is occurring.

67
Js Form Validation

Example: HTML Form

<form action = "data.php" name="myForm" onsubmit = "return vForm();">


<input type = "text" name = "name" >
<input type = "text" name = "email" >
<select name = "country">
<option value = "-1" selected> -- Please Select --</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">Egypt</option>
</select>
<input type = "submit" value = "Submit">
</form>

68
Js Form Validation
Js Code
function vForm() {
if(document.myForm.name.value == "" ) {
alert( "Please Enter Name" );
return false; }
if( document.myForm.email.value == "" ) {
alert( "Please Enter Email" );
return false; }
if( document.myForm.country.value == "-1" ) {
alert( "Please select your country" );
return false; }
return true;
}

69
Js Email Validation

• The email must contain “@” and at least one dot “.”

• The @ must not be in the first or the second position.

• The last dot must be present after the @ sign by at least two digits.

• The last dot must be present at minimum 2 characters before the end

• pattern: [email protected]

70
Js Email Validation
Js Code

function validateMail() {
var x=document.myForm.email.value;
var atIndex=x.indexOf("@");
var dotIndex=x.lastIndexOf(".");
if (atIndex<2 || (dotIndex-atIndex)<2 || x.length-dotIndex<3)
{
alert("Invalid e-mail address");
return false; }
}

71

You might also like