Document Object Model (DOM) Flashcards

1
Q

What is DOM (Document Object Model)? And what are it’s functions? No

A

Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document.
It is representation of HTML document in the browser.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do we breakdown accessing DOM Elements?

A

document.getElementById(‘’).textContent

In above function we access the document object.
Use getElementById method
Which returns another DOM object, that has a property textContent (getElementById is the most optimized method)
If we want to access the class, we need to write .className or .classList

We can also access DOM elements by:
document.querySelector(‘.description’) (using selectors like in CSS)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Accessing document object

A

document. documentElement
document. body
document. images

We can also access all elements according to selector query: document.querySelectorAll(‘’), but then we need to work with a node list (węzły)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How can you access computed style properties of elements, such as fontsize?

A

simple .style.fontSize might not work, because the style property only contains inline styles (not calculated styles or styles from the stylesheet). This will result in an empty string “” even though the element has a style.

window.getComputedStyle ()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you access images in the DOM?

A
You can easily create an array for images.
For the whole document:
const imgs = Array.from(document.images);
or const imgs = [...document.images];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What are the methods that allow to access single dom element?

A

document. querySelector(‘li:nth-child(2)’);
document. getElementById(‘first’);

Both methods will find the first element in the document or return null.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the methods that allow accesing all matching elements?

A

document. querySelectorAll(‘ul>li’);
document. getElementsByTagName(‘li’)
document. getElementsByClassName(‘even’)

querySelectorAll is better supported and has more array methods.
getElementsByTagName and getElementsByClassName allows for search in other DOM objects than document. For instance, you can search in ul element.
Spread operator might also be useful to access the array methods, if they are needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How can you modify elements?

A

You can either assign values directly to the attributes or add/remove classes.

firstLi.textContent = “Nowa zawartość tekstowa”;
firstLi.innerHTML = ‘<strong>Pogrubienie</strong> i normalnie’;
firstLi.style.backgroundColor = “#ccc”
firstLi.classList;
firstLi.className;

It is important to know that all the elements we change from JS are added linearly to HTML (not to the outer Css file)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the methods to manipulate classes of elements?

A

classList.add(‘myClass’);
classList.contains(‘myClass’);
classList.remove(‘myClass’);
classList.toggle(‘myClass’);

className = “one two”; (will overwrite old values with new value)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you listen and handle DOM events?

A

element. addEventListener(‘click’, function () {})
window. addEventListener(‘‘scroll’, function () {})

document.querySelector(‘h1’).addEventListener(‘click’, function () {
this.textContent = “”;
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the methods to add elements to a page?

A
First, we need to create an element Li
const liElement = document.createElement('li');
liElement.textContent = "Ostatni"; //add classList etc.

ul.appendChild(liElement);
ul.insertBefore(newLi,secondLi) (will insert the element befor secondLi in the ul element).
firstLi.insertAdjacentElement(‘beforebegin’,liElement) - Interesting method

append, prepend are new methods(that do not work in IE) Allow to insert multiple elements like:
firstP.append(i, newLi);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the basic properties of mousemove event?

A

Whenever we add event listener, we are given an event object. Some of mousemove event object basic properties are:

e. clientX, e.clientY (position from start of the window)
e. pageX, e.pageY
e. offsetX, e.offsetY

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is the difference between key capturing events in the DOM

A

there are 3 methods to capture key events.
‘keyup’
‘keydown’
‘keypress’

keypress is meant to be event that captures letters that are put into an input. (so it does not capture keys like arrow up, tab etc.) (what is interesting delete and backspace will not be considered as a key press too.)
keyup and keydown capture all kinds of keys.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How do you get number of pixels that the document has been scrolled horizontally or vertically

A

window.pageXOffset, window.pageYOffset;

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does Element.getBoundingClientRect() method do?

A

It returns the size and position of an element relative to the viewport.
getBoundingClientRect().top, will return its position from the top of the viewport.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you access html element data attribute?

A

By using this.dataset.(attribute name)

17
Q

What are the methods to access text inside of an HTML element?

A

p. innerText
p. textContent

however, both of those methods behave differently. textContent is faster, however it just removes the tags from the text that is displaying. Meaning, it will show elements that are hidden or set to display: none.
While innerText interprets which elements should be visible and formats the text a clear block

18
Q

What does innerHTML do?

A

innerHTML will produce a string that groups all elements between the two tags.
It will give all of the content that is in there.

ul.innerHTML
"
    <li class="special">First Thing</li>
    <li>Second Thing</li>
    <li class="special">Third Thing</li>
19
Q

How do you access values inside of HTML elements?

A

The property that shows the value of the element/input element depends on the type of the el.

  • For password, text, textarea, range elements we can access them by .value
  • For checkboxes we can access them by .checked
  • For anchors we can access the .href
  • For images we can access the img .src
20
Q

How can you access neighbour properties of an HTML element?

A

There are situations when you might need to access and change parent, children or sibling elements.

.parentElement
.children
.nextElementSibling
.previousElementSibling

21
Q

What are the methods to remove elements from the DOM?

A

ul. removeChild(li);
li. remove()

First method works in IE, we need to target a parent element and remove the child.
In .remove() case, we just can remove the element.

22
Q

What are the differences when it comes to ‘input’ and ‘change’ events?

A

When it comes to listening to form inputs, input, will incrementally check after values are added to the input, while change will check the values after we press enter or tab (in other words -> lose focus)

23
Q

What does it mean to debounce an input?

A

This is a pattern that allows us to wait some time to pass after the last registered event to actually do something.

We can implement it with setTimeout function.
Debouncing a scroll, or widget search results

let timeoudId;

const inputChange = e => {
    if (timeoutId) {
        clearTimeout(timeoutId);
    }
    timeoutId = setTimeout(() => {
        // movie.fetchMovieData(e.target.value)
    }, 1000);
}
24
Q

What are methods and events that allow us to start or stop a video?

A

const video =

video. play();
video. pause();

Useful events that come together with videos are
video.addEventListener(‘play’, func)
‘pause’, func
video.addEventListener(‘timeupdate’, func)

25
Q

What are useful properties of video (HTMLMediaElement)

A

video. currentTime
video. duration
video. ended
video. muted
video. paused
video. playbackRate
video. volume

26
Q

How can you toggle full screen with video element?

A

const player (parentDiv of )

player. requestFullscreen();
document. exitFullscreen();

27
Q

What is event bubbling?

A

When an event happens on an element, it first runs the handlers on it, then on its parent, then all the way up on other ancestors.
The process is called “bubbling”, because events “bubble” from the inner element up through parents like a bubble in the water.

28
Q

What is the difference between bubbling and capturing?

A

In modern browsers, the browser will first do a capture:
- When you click on an element, it’s going to ripple down, goes top-down and captures where the user has clicked.
Then, the events will bubble up, -> triggering the events as we go up.

To stopPropagation of events we can add e.stopPropagation() to our function.

When listening for events we can decide about the options arguments that we want to pass (by default false):

element.addEventListener(‘click’, myClickHandler, {
once: true,
passive: true,
capture: true
});

29
Q

What are the features of drag-and-drop api?

A

This interface enables applications to use drag and rdop features in the browsers. The user may select draggable elements with a mouse and drag tohse elements to a droppable element.

In order to mark an element draggable, we need to set up it’s draggable property to true.

Then, we can access its drag events (dragstart, dragend).
Droppable elements can be assigned properties like dragover, dragenter, dragleave or drop.

30
Q

What’s the best way to find an ancestor element?

A

Using closest() method we can find an element in the dom tree that matches passed in selector.

It is especially useful, when it comes to click inside/outside of modals.

31
Q

What method is useful, when it comes to Event delegation?

A

Event delegation allows us to attach single event listener to a parent element, that will fire for all descendants matching a selector.
This technique makes use of even propagation (bubbling) to handle events at a higher levet in the dom tree than the element on which it originated.

e.target.matches(‘button’)

or e.target.tagName === ‘STH’

32
Q

What’s the difference between offset, client and scroll im the box model?

A

clientHeight returns the inner height of an element in pixels, including padding butnotthe horizontalscrollbar height,border, ormargin

offsetHeight is a measurement whichincludesthe elementborders, the element vertical padding, the element horizontalscrollbar(if present, if rendered) and the element CSS height.

scrollHeight is a measurement of the height of an element’s contentincludingcontentnot visibleon the screendue to overflow

33
Q

What are the properties for offset, client and scroll of elements in box model?

A

el.scrollLeft, el.scrollHeight, el.scrollTop, el.scrollWidth

34
Q

What is the purpose of Shadow DOM and encapsulation?

A

The Shadow DOM API provides a way to attach a hidden separated DOM to an element. It is used to encapsulate the inner structure of the elements that are attached to the DOM.

Encapsulation — being able to keep the markup structure, style, and behavior hidden and separate from other code on the page so that different parts do not clash, and have reduced complexity

35
Q

What are the methods and properties used to create custom elements?

A
  1. To begin with, the JavaScript file defines a class called PopUpInfo, which extends the generic HTMLElement class.
  2. We need to always call super() inside the constructor function.
  3. Inside the constructor, we attach a shadow root to the custom element, use DOM manipulation to create the element’s internal shadow DOM structure — which is then attached to the shadow root — and attach CSS to the shadow root.
    const root = this.attachShadow({mode: ‘open’}); // sets and returns ‘this.shadowRoot’
This all can be done with root.innerHTML = ``;
4. Finally, we register our custom element on the CustomElementRegistry using the define() method we mentioned earlier — in the parameters we specify the element name, and then the class name that defines its functionality:

customElements.define(‘popup-info’, PopUpInfo);

  1. It is now available on our page:
36
Q

How can you extend built in elements?

A
  1. To extend an element, you’ll need to create a class definition that inherits from the correct DOM interface. For example, a custom element that extends needs to inherit from HTMLButtonElement instead of HTMLElement.
  2. customElements.define(‘fancy-button’, FancyButton, {extends: ‘button’}).
    Notice that the call to define() changes slightly when extending a native element. The required third parameter tells the browser which tag you’re extending. This is necessary because many HTML tags share the same DOM interface. , <address>, and <em> (among others) all share HTMLElement; both and <blockquote> share HTMLQuoteElement; etc.. Specifying {extends: ‘blockquote’}</em>
  3. Consumers of a customized built-in element can use it in several ways. They can declare it by adding the is=”” attribute on the native tag:
    TestMy Button</blockquote></em></address>
37
Q

What are the technologies that make up Web Components?

A
  1. Custom Elements. Quite simply, these are fully-valid HTML elements with custom templates, behaviors and tag names (e.g. ) made with a set of JavaScript APIs. Custom Elements are defined in the HTML Living Standard specification.
  2. Shadow DOM. Capable of isolating CSS and JavaScript, almost like an . This is defined in the Living Standard DOM specification.
  3. HTML templates. User-defined templates in HTML that aren’t rendered until called upon. The tag is defined in the HTML Living Standard specification.
38
Q

What is the difference between throttling and debouncing?

A

Throttling will delay executing a function. It will reduce the notifications of an event that fires multiple times.

Debouncing will bunch a series of sequential calls to a function into a single call to that function. It ensures that one notification is made for an event that fires multiple times.