I have started learning javascript and will use this post as notes for later.
JavaScript uses camelCase where CSS uses kebab-case.
CSS JavaScript
background-color backgroundColor
color color
font-size fontSize
z-index zIndex
[ ] = Array
{ } = Object
1_000_000 = 1.000.000 det er bare mere læseligt
Callback = A callback is a function passed as an argument to another function
Constructor = Function som automatisk bliver kørt i en klasse
#varNavn = private Instance variable. Disse kan ikke bruges i en constructor uden at deklarere variablen først.
#privateMethod() = private instance method
JSON.parse(string) = konvertere JSON string til JSON Object
JSON.stringify(object) = konvertere JSON Object til JSON string
Nullish coalescing
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand
const foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase() ?? "not available"); // "HI"
console.log(foo.someBarProp?.toUpperCase() ?? "not available"); // "not available"
Fetch()
This .json() method on response is almost exactly the same as JSON.parse(string) that you used in the previous chapter. The only difference however is that response.json() is non-blocking and asynchronous meaning that it returns a promise
Implicit return
Whenever you have a function that has a body of only 1 line and returns the result of that one line, you can omit the return and write it in a shorter syntax
Just like how fetch(URL) returns a promise, the response.json() method also returns a promise. This means that we cannot read its result directly. Instead, we have to resolve the promise with .then(callback).
It’s extremely important to add a console.log(data) the first time you work with a URL so that you can see, visualize & understand what kind of data this API (and this particular URL) is returning.
HTML & Javascript
You can access the DOM in JavaScript with the document variable.
The document.querySelector() (note the capital S character) method expects a CSS selector. That’s the same as the selectors you’d write in your CSS file.
document.querySelector(“CSS-selector”) returns an object which is an instance of HTMLElement. HTMLElement is the parent class that every single HTML element in your page inherits from. This means that every element on your page is an instance of a single class which is HTMLElement
## Type selectors
<h1>Big Headline</h1>
<script>
const title = document.querySelector(“h1”);
</script>
## ID selector
<div id=“navbar”></div>
<script>
const navbar = document.querySelector(“#navbar”);
</script>
## Class selector
<div class=“item”></div>
<script>
const item = document.querySelector(“.item”);
</script>
## Descendant selector
<div id="banner">
<div class="item"></div>
</div>
<script>
// "space character" ( ) for descendant
const item = document.querySelector("#banner .item");
</script>
## Attribute selector
<input type="text" placeholder="Your name here" disabled>
<script>
// find the element with the disabled attribute
document.querySelector("[disabled]");
</script>Element.textContent
The textContent property returns the text that’s in between the opening tag (for example,
Finding multiple elements
document.querySelectorAll(“CSS-selector”);
While document.querySelector() might return null (when no items are found), the document.querySelectorAll() will always return a NodeList. This is an important difference.
<p id="first">First paragraph</p>
<p id="second">Second paragraph</p>
document.querySelectorAll("p"); // NodeList(2) [p#first, p#second]
const items = [...document.querySelectorAll("div")]; // Array
As you can see, you can convert a NodeList into an array using the array spread syntax (…) which spreads every single item of the NodeList, into a new array.
Element.innerHTML
innerHTML will return the HTML string inside of the element (it will not strip out HTML tags). Where textContet will return the text with all HTML tags removed.
If the string that you’re rendering is coming from your users (for example, a string coming from a comment box that the user can fill), then you should avoid using innerHTML as your users will be able to write HTML & JavaScript code inside of your page which may lead to security issues. This is called Cross-Site Scripting (XSS) attack.
Element.value
To read the written content of an input element, you have to use value property:
Element.classList
element.classList returns an object containing methods that let you manage the classes of an element.
element.classList.add(className) will add the class.
element.classList.remove(className) will remove the class.
element.classList.contains(className) returns true when the element has the class and false otherwise.
element.classList.toggle(className) will add it when it’s not already present and remove it otherwise.
element.classList.replace(oldClassName, newClassName) will replace the oldClassName with the newClassName.
element.classList.add() can be used to add multiple classes at the same time.
element.classList.remove() can be used to remove multiple classes at the same time.
element.getAttribute(key) gets the value of a certain attribute by its key.
element.removeAttribute(key) removes an attribute.
element.setAttribute(key, value) writes a new attribute (or updates the value of an old one that already exists).
element.hasAttribute(key) checks whether an attribute exists or not. It always returns a boolean.
Element.remove()
Completely removes the element from DOM where innerHTML empties the content of the element.
document.body
If you need to access the
element of the page, instead of finding it with querySelector, you can access it with document.body directlydocument.documentElement
Accesstag directly with document.documentElement
Dataset
element.dataset returns an object containing all the data- attributes on that element.
Data attribute names are converted from kebab-case to camelCase.
Data values are always saved as a string. value === “true” allows you to convert “true” and “false” into a boolean.
element.parentElement
The element.parentElement property returns the parent element of the current element.
element.closest(“CSS-selector”)
The element.closest(“CSS-selector”) method returns the closest parent that matches the CSS-selector you specified. It searches for parent elements and goes up one by one.
element.insertAdjacentHTML(position, htmlString)
The element.insertAdjacentHTML will place the htmlString without having to reconstruct the remaining HTML inside the element. It could either prepend or append depending on the position that you provide.
innerHTML += … is inefficient because it recreates the entire HTML. This could also remove existing event listeners.
Instead, when you want to add a piece of HTML, you should use the insertAdjacentHTML method.
element.insertAdjacentHTML(position, htmlString) will prepend/append the htmlString depending on the position.
A position of beforeend will append (add at the end).
A position of afterbegin will prepend (add at the beginning).
document.createElement
For example, instead of writing the htmlString
Hello World
, you can construct it with the document.createElement() method:const paragraph = document.createElement("p");
paragraph.classList.add("text-center");
paragraph.textContent = "Hello World";
console.log(paragraph); // <p class="text-center">Hello World</p> (as an element not as a string)
You can then use the element.appendChild() method to append it somewhere in the DOM. For example:
document.body.appendChild(paragraph);document.addEventListener
The element.addEventListener(eventType, callback) method allows you to wait for an event to happen on an element. Once that event occurs (the user clicks on the button), the callback function will execute.
The event.currentTarget refers to the element to which the event listener has been attached.
event.preventDefault(); makes disables reload on form submit
form.addEventListener("submit", event => {
event.preventDefault();
// the form will not reload anymore
});-focus is triggered when the user enters focus (the cursor) in a textbox.
-blur is triggered when the user removes focus (the cursor) from a textbox.
-DOMContentLoaded is fired when the browser has finished loading & constructing the entire HTML on your page.
-scroll is triggered every time the user scrolls.
-change is used to know when a
Event bubbleing
<a class="card">
<button>close</button>
</a>
document.querySelector(".card").addEventListener("click", event => {
console.log("Card clicked");
});
document.querySelector(".card button").addEventListener("click", event => {
console.log("Close clicked");
});Clicking on the close button will make both events fire due to event bubbling. You can disable that by calling event.stopPropagation():