Var El Document - Queryselector ('H1') Console - Log ('El:', El)
Var El Document - Queryselector ('H1') Console - Log ('El:', El)
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>
Select the first element with the selector statement .main .title .t1.
document.querySelector(".main .title .t1")
NodeList -- 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>
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>
<script>
// Selecting element
var elem = document.getElementById('intro');
<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);
<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>
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`)
}