Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Select Elements

--- Find Element By ID

document.getElementById("my-div");

-this usually used to get an element using the ID

--- Find Element By Tag Name

let myTagElements = document.getElementsByTagName("p");

-this usually used to get all elements that has the targeted tag

-You deal with it as an array of element

console.log(myTagElements[1]);

--- Find Element By Class Name

let myClassElement = document.getElementsByClassName("my-span");

-this usually used to get an element using the class name

--- Find Element By CSS Selectors

let myQueryElement = document.querySelector(".my-span");

-this usually used to get an element using the class name and using the
dot notation.

let myQueryAllElement = document.querySelectorAll(".my-span");

-this usually used to get an all element using the class name and using
the dot notation.

-You deal with it as an array to access a specified element using the


indexes

console.log(myClassElement[1]);

Note: it can be used using the the symbol # before the ID name

Note: to get an element using the name use the following pattern

document.querySelector("[name='username']");
--- Find Element By Collection

------ title

console.log(document.title);

-This return the title of the web page.

------ body

console.log(document.body);

-this return all the element inside the body of the HTML document

------ images

console.log(document.image);

-This return an all images inside a web page

------ forms

console.log(document.forms);

-This return all the forms in the page inside and array,and you access
them using indexes.

For example : console.log(document.forms[0]);

Note: to access and element inside the form you assigned a value to
name attribute and use the value to access it

For example : console.log(document.forms[0].one);

<input type="text" value="ahmed" name="one">

Note: to access the value inside use the value attribute with dot
notation.

For example : console.log(document.forms[0].one.value);

Note: you can also access all element of the from using

Document.forms[“from-one”].element[index];

------ links

console.log(document.links);

-This will return all the link element inside a body and store them in
array.
Note: to access an attribute use the attribute name with dot notation
and this we return the value stored in that attribute

For example : console.log(document.links[1].href);

Get, Set Elements Content And Attributes


let myElement = document.querySelector(".js");

DOM [Get / Set Elements Content And Attributes]

- innerHTML

console.log(myElement.innerHTML);

-This will return the entire text inside the HTML tag including any tag
inside the text

- textContent

console.log(myElement.textContent);

-This will return the entire text inside the HTML tag ignoring any tag
inside the text

myElement.innerHTML = "Text From <span>Main.js</span> File";

-When you change the text inside the HTML tag using the innerText

It will ignore any tag inside the text

myElement.textContent = "Text From <span>Main.js</span> File";

-When you change the text inside the HTML tag using the innerText

It will write down any tag inside the text

- Change Attributes Directly

document.images[0].src = "https://google.com";

document.images[0].alt = "Alternate";

document.images[0].title = "Picture";

document.images[0].id = "pic";

document.images[0].className = "img";
- Change Attributes With Methods

let myLink = document.querySelector(".link");

- getAttribute

console.log(myLink.getAttribute("class"));

console.log(myLink.getAttribute("href"));

-This will return the value stored in that attribute.

- setAttribute

myLink.setAttribute("href", "https://twitter.com");

myLink.setAttribute("title", "Twitter");

-This will change the value of an attribute


Check Attributes And Examples
- Element.attributes

console.log(document.getElementsByTagName("p")[0].attributes);

-This method gets all attributes store inside an element as an array

- Element.hasAttribute

myP.hasAttribute("data-src");

-This method return a boolean if an specific attribute exist or not.

- Element.hasAttributes

if (document.getElementsByTagName("div")[0].hasAttributes()) {

console.log(`Has Attributes`);} else {

console.log(`Div Has No Attributes`);

-This method return boolean expression if there is any attribute or


not.

- Element.removeAttribute

if (myP.hasAttribute("data-src")) {

if (myP.getAttribute("data-src") === "") {

myP.removeAttribute("data-src");

} else {

myP.setAttribute("data-src", "New Value");

}} else {

console.log(`Not Found`);

-This method remove a specific attribute from inside a tag


Create And Append Elements

- createElement

let myElement = document.createElement("div");

-This create an element inside the html page.

- createComment

let myComment = document.createComment("This Is Div");

-This method used to create a comment and it used with appendChild() to


add the comment

- createTextNode

const h1 = document.createElement("h1");

const textNode = document.createTextNode("Hello World");

-This method create a text object and you can append it to and other
tag

h1.appendChild(textNode);

- createAttribute

let myAttr = document.createAttribute("data-custom");

-This create an attribute and make it null.

Note: to set an attribute to a node you should use


setAttributeNode(myAttr) or setAttribute("data-test", "Testing")

- appendChild

myElement.appendChild(myComment);

myElement.appendChild(myText);

-This method usually used to add a text or comment to a tag


Deal With Children

DOM [Deal With Childrens]

- children

console.log(myElement.children);

-this write all childern of that element exclude all of the node such
text and comment node.

-you deal with it using indexes myElement.children[index]

- childNodes

console.log(myElement.childNodes);

-this write all childern of that element include all of the node such
text and comment node.

-you deal with it using indexes myElement.childNodes[index]

- firstChild

console.log(myElement.firstChild);

-this return the frist node.

- lastChild

console.log(myElement.lastChild);

-this return the last node.

- firstElementChild

console.log(myElement.firstElementChild);

-this return the first element excluding the node

- lastElementChild

console.log(myElement.lastElementChild);

-this return the last element exclude the nodes


DOM Events
DOM [Events]

- Use Events On HTML

- Use Events On JS

--- onclick

--- oncontextmenu

-this to change the menu when right click is pressed

--- onmouseenter

--- onmouseleave

--- onload

--- onscroll

--- onresize

Usually with input field

--- onfocus

--- onblur

--- onsubmit

let myBtn = document.getElementById("btn");

myBtn.onmouseleave = function () {

console.log("Clicked");};

window.onresize = function () {

console.log("Scroll");};
Validate Form And Prevent Default
DOM [Events]

- Validate Form Practice

Note: use .value to get the value from the tag and it will return a
string

For example :

document.forms[0].onsubmit = function (e) {

let userValid = false;

let ageValid = false;

if (userInput.value !== "" && userInput.value.length <= 10) {

userValid = true;

if (ageInput.value !== "") {

ageValid = true;

if (userValid === false || ageValid === false) {

e.preventDefault();

}};
- Prevent Default

event.preventDefault();

-this usually used with function to prevent the function from


performing it order

For example:

document.links[0].onclick = function (event) {

console.log(event);

event.preventDefault();

};
Event Simulation – Click, Focus, Blur
/*

let one = document.querySelector(".one");let two =


document.querySelector(".two");

DOM [Events Simulation]

let the browser do the event for you

- click

one.onblur = function () {

document.links[0].click();

};

Whenever you blur after foucs in input for example

- focus

window.onload = function () {

two.focus();

};

To let foucs in something at the begaining

- blur
ClassList Object and Methods
/*

let element = document.getElementById("my-div");

DOM [Class List]

- classList

console.log(element.classList);

This return all the class as list

--- length

console.log(element.classList.length);

This return the length of the classList

--- contains

console.log(element.classList.contains("osama"));

console.log(element.classList.contains("show"));

This check if the classList has a specific class name and return a
boolean value.

--- item(index)

console.log(element.classList.item("3"));

This return the class name with that index

--- add

console.log(element.classList.add("show"));

This add a class call “show”

--- remove

console.log(element.classList.remove("show"));

This remove a class cald “show” if exist

--- toggle

element.onclick = function () {

element.classList.toggle("show");

};

This check if the class exist it will remove it if not it will add it
CSS Styling And Stylesheets
let element = document.getElementById("my-div");

DOM [CSS]

- style

element.style.color = "red";

element.style.fontWeight = "bold";

This for inline styling and change the attribute of one element

- cssText

element.style.cssText = "font-weight: bold; color: green; opacity:


0.9";

This for inline styling and change the attribute of multible elements

In one line.

- removeProperty(propertyName) [Inline, Stylesheet]

element.style.removeProperty("color");

This for inline to remove the a specific color style

- setProperty(propertyName, value, priority)

element.style.setProperty("font-size", "40px", "important");

This for inline to add the a specific style

Note: to change in css style for a specifc style sheet use styleSheet
to select which one and the use the rule to choose which element inside
the styleSheet

document.styleSheets[0].rules[0].style.removeProperty("line-height");

document.styleSheets[0].rules[0].style.setProperty("background-color",
"red", "important");
Before, After, Prepend, Append, Remove
/*

let element = document.getElementById("my-div");

let createdP = document.createElement("p");

DOM [Deal With Elements]

- before [Element || String]

Element.before(createP);

-this method add the created element before the targeted element

- after [Element || String]

Element.before(createP);

-this method add the created element after the targeted element

- append [Element || String]

Element.before(createP);

-this method add the element at the last inside the targeted element

- prepend [Element || String]

Element.before(createP);

-this method add the element at the begaining inside the targeted
element

- remove

element.remove();

-this methed delete the element from the HTML body


DOM Traversing
DOM [Traversing]

let span = document.querySelector(".two");

- nextSibling

console.log(addClasses.nextSibling);

-this method display the next node

- previousSibling

console.log(addClasses.previousSibling);

-this method display the previous node

- nextElementSibling

console.log(addClasses.nextElementSibling);

-this method display the next element

- previousElementSibling

console.log(addClasses.previousElementSibling);

-this method display the preivous element

- parentElement

console.log(span.parentElement);

-this method display the paraent element of a node

span.onclick = function () {

span.parentElement.remove();

}
DOM Cloning
DOM [Cloning]

- cloneNode(Deep)

let myP = document.querySelector("p").cloneNode(true);

let myDiv = document.querySelector("div");

myDiv.appendChild(myP);

- if the deep argument set to true it will copy the element that inside
the the copied element as well.

-take to your considration that the clone element will duplicate the id
and this is wrong so you must change it

myP.id = `${myP.id}-clone`;

Note: appendChiled can set from existing element and move them form
place to another
addEventListener
DOM [Add Event Listener]

- addEventListener

- Use Without On

- Attach Multiple Events

- Error Test

Search

- Capture & Bubbling JavaScript

- removeEventListener

let myP = document.querySelector("p");

// myP.onclick = one;

// myP.onclick = two;

// function one() {// console.log("Message From OnClick 1");// }

// function two() {// console.log("Message From OnClick 2");// }

Note : here using on event the event will only attach the last one,it
will override the others

// window.onload = "Osama";

Note: it will not show a error but event listener it will

// myP.addEventListener("click", function () {

console.log("Message From OnClick 1 Event");

});

// myP.addEventListener("click", one);

// myP.addEventListener("click", two);

Note : here using event listener the event will attach all the function
// myP.addEventListener("click", "String");

// Error

Note: the second parameter only accept js object or function

myP.onclick = function () {

let newP = myP.cloneNode(true);

newP.className = "clone";

document.body.appendChild(newP);

};

// let cloned = document.querySelector(".clone");

// Error

Note: the error because the onclick event does not deal with element
not created yet

// cloned.onclick = function () {//

console.log("Iam Cloned");//

};

document.addEventListener("click", function (e) {

if (e.target.className === "clone") {

console.log("Iam Cloned");

});

Note: no error because the event listener can deal with element not
created yet
setTimeout and clearTimeout
BOM [Browser Object Model]

- setTimeout(Function, Timeout, Additional Params)

-This function is used to perform the function after a set of timeout;

setTimeout(function () {

console.log("Msg");

}, 3000);

-You do not give the argument in the function parameter but you write
them after timeout in order

setTimeout(sayMsg, 3000, "Osama", 38);

function sayMsg(user, age) {

console.log(`Iam Message For ${user} Age Is : ${age}`);

- clearTimeout(Identifier)

-This function is made to stop the setTimeout from runing by giving it


the counter for the setTimeout function

For example

function sayMsg(user, age) {

console.log(`Iam Message For ${user} Age Is : ${age}`);

let counter = setTimeout(sayMsg, 3000, "Osama", 38);

let btn = document.querySelector("button");

btn.onclick = function () {

clearTimeout(counter);

};
setInterval and clearInterval
BOM [Browser Object Model]

- setInterval(Function, Millseconds, Additional Params)

-This function keep repeating the function each millseconds.

- clearInterval(Identifier)

-This function stop the setInterval

For example

let div = document.querySelector("div");

function countdown() {

div.innerHTML -= 1;

if (div.innerHTML === "0") {

clearInterval(counter);

}}

let counter = setInterval(countdown, 1000);

You might also like