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

Var El Document - Queryselector ('H1') Console - Log ('El:', El)

The document summarizes how JavaScript can access and manipulate elements in an HTML document using the Document Object Model (DOM). It explains that the DOM represents the document as nodes organized in a tree structure, and that DOM methods allow programmatic access and manipulation of this tree. Some key DOM methods discussed are querySelector(), getElementById(), querySelectorAll(), getElementsByClassName(), getElementsByTagName(), and ways to get/set attributes, styles, and content of elements. It also covers creating, adding, and removing DOM nodes.

Uploaded by

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

Var El Document - Queryselector ('H1') Console - Log ('El:', El)

The document summarizes how JavaScript can access and manipulate elements in an HTML document using the Document Object Model (DOM). It explains that the DOM represents the document as nodes organized in a tree structure, and that DOM methods allow programmatic access and manipulation of this tree. Some key DOM methods discussed are querySelector(), getElementById(), querySelectorAll(), getElementsByClassName(), getElementsByTagName(), and ways to get/set attributes, styles, and content of elements. It also covers creating, adding, and removing DOM nodes.

Uploaded by

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

avaScript can access all the elements in a webpage making use of Document Object Model (DOM).

In fact, the web browser creates a DOM of the webpage when the page is loaded.
DOM c est un arbre d ele , leur atty et le contenu de la page =construire l arbre sous forme d
hierarchie
The
DOM
represents a document with a
logical tree
. Each branch of the tree ends in a
node
, and each node contains
objects
. DOM methods allow programmatic access to the
tree
. With them, you can change the document's
structure
, style, or content. Nodes can also have
event handlers
attached to them. Once an event is triggered, the event handlers get executed.
Using DOM,JavaScript can perform multiple tasks like :
• Creating new elements and attributes.
• Hanging the existing elements and attributes and even remove existing elements and
attributes.
• Reacting to existing events.
• Creating new events in the page.
JavaScript is most commonly used to get or modify the content or value of the HTML elements on
the page, as well as to apply some effects like show, hide, animations etc. But, before you can
perform any action we need to find or select the target HTML element.
Here is some definition before we start:
Document interface represents any web page loaded in the browser and serves as an entry point into
the web page's content, which is the DOM tree. The DOM tree includes elements such as <body>
and <table>, among many others. It provides functionality globally to the document, like how to
obtain the page's URL and create new elements in the document.
The Document method querySelector() returns the first Element within the document that matches
the specified selector, or group of selectors. If no matches are found, null is returned.
var el = document.querySelector('h1');
console.log('el:', el);

The Document method getElementById() returns an Element object representing the element whose
id property matches the specified string. Since element IDs are required to be unique if specified,
they're a useful way to get access to a specific element quickly.
Syntax: element = document.getElementById(id)
var el = document.getElementById('middleSpan');
The Document method querySelectorAll() returns a static (not live) NodeList representing a list of
the document's elements that match the specified group of selectors.
Syntax: elementList = parentNode.querySelectorAll(selectors);
<body>
<h1>Hello from Mars!</h1>
<span
>Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, quos
eveniet.
</span>
<span id="middleSpan">
Quisquam veritatis, quam velit quos eligendi perferendis fugiat eveniet
</span>
<span>
sapiente ratione assumenda iste repudiandae quidem dicta aliquid.
Voluptatibus, error?
</span>
<script>
var el = document.querySelectorAll('middleSpan');
console.log('el:', el);
</script>

he getElementsByClassName method of Document interface returns an array-like object of all child


elements which have all of the given class name(s). When called on the document object, the
complete document is searched, including the root node. You may also call
getElementsByClassName() on any element; it will return only elements which are descendants of
the specified root element with the given class name(s).
Syntax: elementList = document.getElementsByClassName(names);
<body>
<h1>Hello from Mars!</h1>
<span class="text-desc">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, quos
eveniet.
</span>
<span class="text-desc">
Quisquam veritatis, quam velit quos eligendi perferendis fugiat eveniet
</span>
<span>
sapiente ratione assumenda iste repudiandae quidem dicta aliquid.
Voluptatibus, error?
</span>
<script>
var el = document.getElementsByClassName('text-desc');
console.log('el:', el);
</script>
the getElementsByTagName method of Document interface returns an HTMLCollection of
elements with the given tag name. The complete document is searched, including the root node. The
returned HTMLCollection is live, meaning that it updates itself automatically to stay in sync with
the DOM tree without having to call document.getElementsByTagName() again.
Syntax: elementList = document.getElementsByTagName(name);

How can you retrieve an element with the id #first?


document.getElementById("first")=document.querySelector("#first")

Select the first element with the selector statement .main .title .t1.
document.querySelector(".main .title .t1")

The getElementsByClassName return:


HTML collection

NodeList -- element*

What's DOM Attributes?


The attributes are special words used inside the start tag of an HTML element to control the tag's
behavior or provides additional information about the tag.
JavaScript provides several methods for adding, removing or changing an HTML element's
attribute. In the following sections we will learn about these methods in details.
The getAttribute() method is used to get the current value of a attribute on the element.

If the specified attribute does not exist on the element, it will return null. Here's an example:
<span class="text-desc">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Tempore, quos
eveniet.
</span>
<span class="text-desc">
Quisquam veritatis, quam velit quos eligendi perferendis fugiat eveniet
</span>

The setAttribute() method is used to set an attribute on the specified element.

If the attribute already exists on the element, the value is updated. Otherwise a new attribute is
added with the specified name and value. The JavaScript code in the following example will add a
class and a disabled attribute to the button element.
<button type="button" id="myBtn">Click Me</button>

<script>
// Selecting the element
let btn = document.getElementById('myBtn');
// Setting new attributes
btn.setAttribute('class', 'click-btn');
btn.setAttribute('disabled', '');
</script>

The removeAttribute() method is used to remove an attribute from the specified element.
<body>
<button type="button" class="click-btn" id="myBtn">Click Me</button>

<script>
// Selecting the element
let btn = document.getElementById('myBtn');
// removing class attribute
btn.removeAttribute('class');
console.log('btn:', btn);
</script>

The attributes are only specified to DOM. //false


The getAttribute method return null when it does not find any attribute with the specified name
//true
The setAttribute method accept only one parameter //false
We can also apply style on HTML elements to change the visual presentation of HTML documents
dynamically using JavaScript.
We can set almost all the styles for the elements like, fonts, colors, margins, borders, background
images, text alignment, width and height, position, and so on.
<p id="intro">This is a paragraph.</p>
<p>This is another paragraph.</p>

<script>
// Selecting element
var elem = document.getElementById('intro');

// Appling styles on element


elem.style.color = 'blue';
elem.style.fontSize = '18px';
elem.style.fontWeight = 'bold';
console.log('elem:', elem);
</script>
We can explicitly create new element in an HTML document, using the document.createElement()
method.
This method creates a new element, but it doesn't add it to the DOM.

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
// Creating a new div element
var newDiv = document.createElement('div');
// Creating a text node
var newContent = document.createTextNode('Hi, how are you doing?');
// Adding the text node to the newly created div
newDiv.appendChild(newContent);
// Adding the newly created element and its content into the DOM
var currentDiv = document.getElementById('main');
document.body.appendChild(newDiv, currentDiv);
</script>

e can also get or set the contents of the HTML elements easily with the innerHTML property.
This property sets or gets the HTML markup contained within the element i.e. content between its
opening and closing tags.
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>

<script>
// Getting inner HTML conents
var contents = document.getElementById('main').innerHTML;
console.log('contents', contents);

// Setting inner HTML contents


var mainDiv = document.getElementById('main');
mainDiv.innerHTML = '<p>This is <em>newly inserted</em> paragraph.</p>';
</script>
Similarly, we can use the removeChild() method to remove a child node from the DOM.
This method also returns the removed node

<body>
<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
var parentElem = document.getElementById('main');
var childElem = document.getElementById('hint');
parentElem.removeChild(childElem);
console.log("parentElem", parentElem)
</script>

<div id="main">
<h1 id="title">Hello World!</h1>
<p id="hint">This is a simple paragraph.</p>
</div>
<script>
var parentElem = document.getElementById('main');
var childElem = document.getElementById('hint');
parentElem.removeChild(childElem);
console.log("parentElem", parentElem)
</script>

Add Events
Events refer to what happens to an HTML element, such as clicking, focusing, or loading, to which
we can react with JavaScript.
We can assign JS functions to listen for these events in elements and do something when the event
has occurred.
Here is a list of events. There are three ways you can assign a function to a certain event.
If foo() is a custom function, you can register it as a click event listener (call it when the button
element is clicked) in three ways:
// first way
<button onclick=foo>Alert</button>
// the second way
<div id="main">
<button>Alert</button>
</div>
<script>
// Getting the button
var btn = document.querySelector('button');
btn.onclick=foo;
</script>
// the third way
<div id="main">
<button >Alert</button>
</div>
<script>
// Getting the button
var btn = document.querySelector('button');
btn.addEventListener('click', foo);
</script>

The removeEventListener() method detaches an event listener previously added with the
addEventListener() method from the event it is listening for.
<div id="main">
<button onclick="foo">Alert</button>
</div>
<script>
// Getting the button
let btn = document.querySelector('button');
// Remove the event listener
btn.removeEventListener('click',foo);
</script>

<button id="myBtn">Click Me</button><script> function firstFunction() {alert("The first function


executed successfully!");}function secondFunction() {alert("The second function executed
successfully");} let btn = document.getElementById("myBtn");btn.onclick =
firstFunction;btn.onclick = secondFunction;</script>

Form validation
The form validation process typically consists of two parts— the required fields validation which is
performed to make sure that all the mandatory fields are filled in, and the data format validation
which is performed to ensure that the type and format of the data entered in the form is valid.
Well, let's get straight to it and see how this actually works.
<form name="loginForm" onsubmit="return validateForm(event) ">
<label for="Name">Name:</label>
<input type="text" name="name" placeholder="[email protected]" />
<label for="password">Password:</label>
<input type="password" name="password" placeholder="*********" />
<button type="submit">Login</button>
<button type="reset">cancel</button>
</form>
</body>

function validateForm(e) {
e.preventDefault()
var name = document.loginForm.name.value
var password = document.loginForm.password.value
if (name.length==0)
return alert(`name is required`)
if (password.length<5)
return alert(`password length should more than 5`)
}

function validateEmail() {var emailID = document.myForm.EMail.valuevar atpos =


emailID.indexOf('@') var dotpos = emailID.lastIndexOf('.')if (atpos < 1 || dotpos - atpos < 2)
{alert('Please enter correct email ID')document.myForm.EMail.focus()return false}return true}

You might also like