1/51
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
---|
No study sessions yet.
What is DOM short for?
Document Object Model
What is DOM?
a tree structure of an HTML page, a list of every single element within the HTML
What is HTML?
HyperTextMarkupLanguage: a markup language for content and structure creation of a www page.
How does the HTML code look like?
<! DOCTYPE html>
<html>
<head>
<title>Visualisation Exercise</title>
</head>
<body>
<h1>Intro to Web Stack</h1>
<p>HTML? DOM? </p>
</body>
</html>
Creating and Appending Elements from the DOM?
let body = document.body
let new_para = document.createElement("p") Creates a new paragraph element.
body.appendChild(new_para) Appends the newly created paragraph element to the document.body.
let new_ul = document.createElement("ul") Creates a new unordered list element (<ul>)
new_para.appendChild(new_ul)
Appends the newly created unordered list to the previously created paragraph.
Require/select elements from the DOM
let x = document.getElementById("x")
let y = document.getElementByClassName("y")
let z = document.getElementsByTagName("z")
let a = document.querySelector("a")
let b = document.querySelectorAll("b")
Selects all elements that match a specified CSS selector.
Get Element by ID
let li4 = document.getElementById("li4")
console.log(li4)
Get Elements by Classes
let list = document.getElementsByClassName("aList")
console.log(list)
let lis = document.getElementsByClassName("listItem")
console.log(lis)
let ps_per_Tag = document.getElementsByTagName("p")
console.log(ps_per_Tag)
let lis_per_Tag = document.getElementsByTagName("li")
console.log(lis_per_Tag)
JS code of how to get, check, and set classes for elements
<body>
<div id="exampleElement" class="default-class"></div>
<script>
// Get the element by its ID
const element = document.getElementById('exampleElement');
// Get the current classes of the element
const currentClasses = element.className;
console.log('Current classes:', currentClasses);
// Set classes for the element
element.className = 'new-class-1 new-class-2';
console.log('New classes set:', element.className);
// Check if the element has a specific class
const hasNewClass = element.classList.contains('new-class-1');
console.log('Does the element have "new-class-1"?', hasNewClass);
</script>
</body>
</html>
Query Selector
let p_per_Query = document.querySelector("p")
console.log(p_per_Query)
let ps_per_Query = document.querySelectorAll("p")
console.log(ps_per_Query)
let lis_with_class = document.querySelectorAll(".listItem")
console.log(lis_per_Tag)
Set Style to a list element
li4.style.color = "green"
li4.style.background = "black"
JS code of how to get, check, and set styles with SVG
<body>
<svg width="100" height="100">
<circle id="exampleCircle" cx="50" cy="50" r="40" fill="red" />
</svg>
<script>
// Get the SVG element by its ID
const circle = document.getElementById('exampleCircle');
// Set style for the SVG element
circle.style.fill = 'blue';
circle.style.strokeWidth = '2px';
circle.style.stroke = 'black';
// Check style for the SVG element
const fillStyle = circle.style.fill;
console.log('Fill style:', fillStyle);
// Get computed style for the SVG element
const computedStyle = window.getComputedStyle(circle);
const computedFillStyle = computedStyle.fill;
console.log('Computed fill style:', computedFillStyle);
</script>
</body>
</html>
Modifying Elements from DOM
Modifies attributes and classes of the new unordered list.
new_ul.setAttribute("id","my_very_first_list") //adds the id
new_ul.removeAttribute("id") //removes the id
new_ul.setAttribute("nonsenseA", "nonsenseV")// change A to V
console.log(new_ul.hasAttribute("none"))
console.log(new_ul.classList)
new_ul.classList.add("specialList")
new_ul.classList.add("firstList")
new_ul.classList.add("aList")
console.log(new_ul.classList)
console.log(new_ul.classList.contains("aList"))
console.log(new_ul.classList.contains("secondList"))
Removing Elements from DOM
first_list_item.remove(): Removes the first list item from the DOM.
Get and set elements by style
const x = document.getElementById("x");
x.style.color = "green";
x.style.background = "black"
JS code of how to loop over an array of objects
// Sample array of objects
const data = [
{ id: 1, name: 'John', age: 30 },
{ id: 2, name: 'Alice', age: 25 },
{ id: 3, name: 'Bob', age: 35 }
];
// Looping over the array of objects
for (let i = 0; i < data.length; i++) {
const item = data[i];
console.log(`ID: ${item.id}, Name: ${item.name}, Age: ${item.age}`);
}
Loop for each object
for (let i = 0;i<5;i++){
let new_li = document.createElement("li")
if (i==0) first_list_item = new_li
new_li.innerText = "List item number " + (i+1)
new_li.setAttribute("id","li"+(i+1))
new_li.classList.add("listItem")
new_li.addEventListener("mouseover", e => e.target.style.fontSize = "14pt")
new_li.addEventListener("mouseout", e => e.target.style.fontSize = null)
new_li.addEventListener("click",e => e.target.style.color == "blue" ? e.target.style.color = null : e.target.style.color = "blue")
Iterate over Data Structures - for .. in loop (code)
const person = {fname:"John", lname:"Doe", age:25}; // Having a regular object
for (const info in person) { // for .. in // Used to loop through objects
console.log(info)
}
in keyword = in the object
Iterate over Data Structures - standard for loop (code) → explanation [repeat action for every item in the list]
const array1 = ['a', 'b', 'c']; // Having a regular array
for (let i = 0; i < array1.leght; i++) { // Standard for loop
console.log(array1[i])
}
Iterate over Data Structures - for .. of loop (code)
for (const element of array1) { // for .. of // Used to loop through arrays
console.log(element);
}
of keyword = of this array
Iterate over Data Structures - forEach (..) Callback (code)
const array1 = ['a', 'b', 'c']; //Having the same array again
array1.forEach(function(element) { //calling an anonymous callback function for each element of the array
console.log(element)
})
array1.forEach(element => {console.log(element)}) //As arrow function in one line
arry1.forEach((element, index) => { //Index is the seconf parameter, if you need one
console.log(index + ': ' + element)
})
What is SVG short for?
Scalable Vector Graphics
CSV Coordinate System
It consists of an x-axis (horizontal) and a y-axis (vertical), with the origin (0,0) typically located at the top-left corner of the SVG canvas
The foundation of SVG
>Basic shapes: Lines, rectangles, circles, ellipses, polygons, polylines
>Advanced shapes: Arcs, Quadratic Bezier Curves, Cubic Bezier Curves
>Text
>Opacity and Layering
>Gradients: Linear, radial, opacity, text
>Transformations
>Animations
>Use Cases: Graphs, Bar Charts, Pie Charts
Different ways to add SVGs to HTML
>iframe = give it an address will be rendered on its own and will be put on the website.
>Use it as an image
>use embed
>an image in a CSS file.
The usual way is to have it in an SVG tag (<svg> </svg>)
How SVG is incorporated in the DOM
A special part of the DOM tree
The SVG DOM allows attributes to be accessed even though they haven't been specified explicitly in the document markup
Inline SVG, external SVG file, or embedded SVG using <use>.
Differences between SVG and Canvas
SVG - vector graphics, special part of the DOM tree, persistent elements/nodes, element-specific interaction, gets slower with the number of elements
Canvas - bitmap-based, image in the DOM tree, graphical elements need to be drawn and managed in Javascript, interaction occurs in canvas, mostly better performance
Example of adding an event listener to SVG code
<svg width="100" height="100">
<circle cx="50" cy="50" r="40" fill="red" />
</svg>
<script>
// Get the SVG element
const svgElement = document.querySelector('svg');
// Add an event listener to the SVG element
svgElement.addEventListener('click', function(event) {
console.log('SVG clicked!');
console.log('X-coordinate:', event.clientX);
console.log('Y-coordinate:', event.clientY);
});
</script>
Draw a circle with SVG
<svg><circle cx="40" cy="40" r="24" style="stroke:#006600; fill:#00cc00"/></svg>
Draw a rectangle with SVG
<svg><rect x="10" y="10" height="50" width="50"rx="5" ry="5"style="stroke:#006600; fill: #00cc00"/></svg>
Draw a ellipse with SVG
<svg><ellipse cx="50" cy="50" rx="40" ry="30" style="stroke: #ff0000;stroke-width: 5; fill: none;"/></svg>
Draw a polygon with SVG
<svg><polygon points="10,0 60,0 35,50" style="stroke:#660000; fill:#cc3333;" /></svg>
Draw lines (line and polyline) with SVG
Lines:<svg><line x1="0" y1="10" x2="0" y2="100" style="stroke:#006600;" /></svg>
Polyline:<svg><polyline points="10,2 60,2 35,52 10,2" style="stroke:#006600; fill: #33cc33;" /></svg>
var (function scope)
Used to declare variables in JS
It's accessible within the function in which it's declared or globally if declared outside any function. Variables declared with var can be redeclared and reassigned. It can escape from IF statements and FOR LOOPS
const (block scope)
Used to declare constants in JavaScrip
Once a value is assigned to a const variable, it cannot be reassigned. However, for complex data types like objects or arrays, the properties or elements of the variable can still be modified.
let (block scope)
Used to declare block-scoped variables in JavaScript.
Value can be changed, only used when I know that the value will be immediately changed later on.
What happens to variables that are declared in the global scope?
variables that are declared in the glocal scope are accessible everywhere and are placed at the top of the code
Local/function scope
refers to the area within a function where variables are declared. In this scope, variables are only accessible within the function in which they are defined and cannot be accessed from outside the function.
Block scope
Variables declared with let and const have block scope, meaning they are only accessible within the block in which they are declared (such as within curly braces {}). This makes code more predictable and helps avoid unintended variable hoisting and scoping issues compared to var, which has function scope or global scope.
(bild exempel)
Strings - Value Types (Implicit Typing)
let d = 'ddddddd'
Numbers - Value Types (Implicit Typing)
let e = 1 + 3
let f = 2.5 + 3.8
Booleans - Value Types (Implicit Typing)
let g = true
let h = false
Empty values, null and undefined - Value Types (Implicit Typing)
let p = null
concole.log(p)
p = undefined
console.log(p)
How to write a function where string is the parameter
function scream(string) {
string = string.toUpperCase () + "!!!"
console.log(string)
}
scream('There is always money in the banana stand')
=> THERE IS ALWAYS MONEY IN THE BANANA STAND!!!
different syntax to:
const whisper = (string) => string.toLowerCase() + '.'
console.log(whisper('THERE ALWAYS MONEY IN THE BANANA STAND' ))
const whisper = function (string) {
return string.toLowerCase () + '.'
}
console.log(whisper('THERE ALWAYS MONEY IN THE BANANA STAND' ))
Global Scope (code)
let fruit = 'banana';
function changeFruit () {
fruit = 'apple';
}
changeFruit();
console.log(fruit); //=> apple
Why is it berry and not lemon?
let fruit = 'banana';
function changeFruit() {
fruit = 'apple';
fruit = 'berry'
}
fruit = 'lemon'
changeFruit();
console log(fruit); //=> berry
Because you call the function after fruit = "lemon"
Local Function Scope (code)
function newFruit() {
var fruit = 'apple';
let fruit2 = 'strawberry';
const fruit3 = 'orange';
}
This does'nt work:
console.log(fruit);
console.log(fruit2);
console.log(fruit3);
Block and Function Scope (code)
function fruitLogger (b) {
if (b == true) {
const es6Fruit = 'blueberry'; // => same for let
var oldSchoolJSFruit = 'pear';
console.log(es6Fruit); // => blueberry
}
console.log(es6Fruit); // Block scope => error! fruit is not defined
console.log(oldSchoolJSFruit); // Function scope => pear
}
fruitLogger(true);
Objects (code)
let car = {} //creating empty object
car['vendor'] = 'FIAT' //Adding a new property/value to the object // Same as car.vendor
car.model = 'Panda* //Adding a new property/value to the object // Same as car['model']
console.log( car.vendor + ' ' + car['model']) // => FIAT Panda
Objects (adding attributes during creation)
let car2 = {
vendor : 'Honda',
model : 'Civic',
wheels : 4,
engine : {cylinders : 4, displacement : 1.8}
}
console.log( car2.vendor + ' ' + car2['model'] // => Honda Civic
Objects and Functions (code)
let car3 = {
vendor : 'VW',
model : 'Polo',
wheels : 4,
engine : {cylinders : 4, displacement : 1.8 }
getName : function() {
return this.vendor + ' ' + this['model']
}
}
console.log(car3.getName()}; // => VW Polo