Создание и добавление элементов dom

Алан-э-Дейл       31.03.2024 г.

The Document Interface

The first line of the TypeScript code uses a global variable . Inspecting the variable shows it is defined by the interface from the lib.dom.d.ts file. The code snippet contains calls to two methods, and .

The definition for this method is as follows:

ts

Pass it an element id string and it will return either or . This method introduces one of the most important types, . It serves as the base interface for every other element interface. For example, the variable in the code example is of type . Also take note that this method can return . This is because the method can’t be certain pre-runtime if it will be able to actually find the specified element or not. In the last line of the code snippet, the new optional chaining operator is used in order to call .

The definition for this method is (I have omitted the deprecated definition):

ts

This is an overloaded function definition. The second overload is simplest and works a lot like the method does. Pass it any and it will return a standard HTMLElement. This definition is what enables developers to create unique HTML element tags.

For example returns a element, clearly not an element that is specified by the HTML specification.

For the first definition of , it is using some advanced generic patterns. It is best understood broken down into chunks, starting with the generic expression: . This expression defines a generic parameter that is constrained to the keys of the interface . The map interface contains every specified HTML tag name and its corresponding type interface. For example here are the first 5 mapped values:

ts

Some elements do not exhibit unique properties and so they just return , but other types do have unique properties and methods so they return their specific interface (which will extend from or implement ).

Now, for the remainder of the definition: . The first argument is defined as the generic parameter . The TypeScript interpreter is smart enough to infer the generic parameter from this argument. This means that the developer does not actually have to specify the generic parameter when using the method; whatever value is passed to the argument will be inferred as and thus can be used throughout the remainder of the definition. Which is exactly what happens; the return value takes the argument and uses it to return the corresponding type. This definition is how the variable from the code snippet gets a type of . And if the code was , then it would be an element of type .

JS fetch JSON POST request

The following example generates a POST request with JSON data.

<script>
    async function doRequest() {

        let url = 'http://httpbin.org/post';
        let data = {'name': 'John Doe', 'occupation': 'John Doe'};

        let res = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(data),
        });

        if (res.ok) {

            // let text = await res.text();
            // return text;

            let ret = await res.json();
            return JSON.parse(ret.data);

        } else {
            return `HTTP error: ${res.status}`;
        }
    }

    doRequest().then(data => {
        console.log(data);
    });

</script>

The request is sent to http://httpbin.org/post.

let data = {'name': 'John Doe', 'occupation': 'John Doe'};

This is the data to be sent.

let res = await fetch(url, {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
    },
    body: JSON.stringify(data),
});

We set the parameter to POST and choose the
for the content type. The data is stringified
to the parameter.

let ret = await res.json();
return JSON.parse(ret.data);

We get the data back as JSON string and parse it into the JSON object.

Object { name: "John Doe", occupation: "John Doe" }

Crossorigin policy

Scripts from one site don’t have access to the scripts of the other one. For example, a script at https://www.instagram.com/ can’t read the user’s mailbox at https://gmail.com.

In other words, one origin (domain/port/protocol) can’t access the content of the other one. Even in case of having a subdomain, these are considered different origins.

The rule above affects the resources from other domains, as well.
An example of a script error.js consisting of a single (bad) function call is demonstrated below:

If you try loading it from the same site where it’s located, you will have this:

A good error report can be seen here:

Uncaught ReferenceError: noSuchFunction is not defined
https://javascript.info/article/onload-onerror/crossorigin/error.js, 1:1

The example of loading the same script from another domain will look like this:

Try it Yourself »

So, there is a different report here:

Script error.
, 0:0

There can be different details, depending on the browser. However, idea remains the same: any information regarding the internals of a script is hidden. The reason is that it is from a different domain.

Still, it is important to know details about errors.

There are services, listening for global errors using window.onerror, saving errors and providing an interface to access and analyze them. So, they make it possible to see real errors, triggered by the users. But, if a script has another origin, no more information will be available.

For allowing cross-origin access, the <script> tag should have the crossorigin attribute. The remote server has to provide specific headers.

Three levels of cross-origin access exist:

  1. No crossorigin attribute — the access is not allowed.
  2. For crossorigin="anonymous" the access is allowed, in case the server responds with the header Access-Control-Allow-Origin including or the origin. Any authorization information or cookies are sent to the remote server.
  3. crossorigin="use-credentials": the access is allowed in case the server sends back the Access-Control-Allow-Origin header with the origin and Access-Control-Allow-Credentials: true. Authorization information and cookies are sent to the remote server.

In case of not having any crossorigin attribute, the access will be prohibited.

So, let’s see how to add it.

You can choose between "anonymous" and "use-credentials".
In the event of not caring about the cookies, "anonymous" is the way to go, like this:

Try it Yourself »

Supposing that the server provides Access-Control-Allow-Origin header, the full error report is ready.

Миксины

Миксины позволяют создавать многократно повторяемые блоки кода. Это практически тоже самое, что и функция в языке программирования.

Объявление миксина начинается с ключевого слова , затем через пробел название миксина.

Как видим, чтобы вызвать миксин необходимо поставить символ и без пробела написать название миксина. Если код миксина выносится в отдельный файл, то в том документе, где он вызывается необходимо его подключить через в верхней части документа.

Аргументы

Миксин может принимать также и аргументы.

У нас есть также возможность установить значения аргументов по умолчанию. Делается это примерно также, как и установка параметров функции по умолчанию в ES6 (ECMAScript 6).

Атрибуты

Помимо аргументов миксины также могут принимать и атрибуты.

Обратите внимание, что атрибуты выводятся через символ. Дело в том, что спец

символы экранируются автоматически и чтобы избежать повторного экранирования мы используем знак . Если вы не хотите экранировать символы, то используйте символ . Наиболее подробнее об этом можете почитать в .

А вот так можно вывести произвольное количество атрибутов:

Неизвестное количество аргументов

В миксинах Pug есть возможность передавать неизвестное количество аргументов, используя синтаксис «rest arguments«.

Setting & Removing Styles (setStyle & removeStyle)

Use the & to add or remove the styles. It accepts four argument.

The first argument is the element to which we want to apply the style. name of the styles is the second argument. The value of the style is the third argument. The last argument is Flags for style variations

1
2
3
4
5

abstractsetStyle(elany,stylestring,valueany,flags?RendererStyleFlags2)void

abstractremoveStyle(elany,stylestring,flags?RendererStyleFlags2)void

 

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

 
//Template
 

<div#hello>Hello !</div>

 
 
//Component

@ViewChild(‘hello’,{staticfalse})divHelloElementRef;

setStyle(){

this.renderer.setStyle(this.divHello.nativeElement,’color’,’blue’);

}
 
 

removeStyle(){

this.renderer.removeStyle(this.divHello.nativeElement,’color’);

}
 

Use the last option RendererStyleFlags2 to add the or to make use of

Setting Up

What is our objective? We want to get the data for all Studio Ghibli films and display the titles and descriptions in a grid. For some background knowledge, Studio Ghibli is a Japanese animation studio that produced several films, such as Spirited Away, which my friend Craig inspired me to use as an example.

We’re going to start by creating an index.html file in a new directory. The project will only consist of index.html, style.css, and scripts.js at the end. This HTML skeleton just links to a CSS and JavaScript file, loads in a font, and contains a div with a id. This file is complete and will not change. We’ll be using JavaScript to add everything from here out.

index.html

Since this article is focused on the concepts of APIs and JavaScript, I will not be explaining how the CSS works. We will create a style.css that will be used to create a grid. For brevity’s sake, I only included the most pertinent structural CSS below, but you can copy the full CSS code here.

style.css

Now we have HTML and CSS set up, so you can make scripts.js and we’ll continue from there.

More Examples

Example

Move a list item from one list to another:

var node = document.getElementById(«myList2»).lastChild;
document.getElementById(«myList1»).appendChild(node);

Before appending:

  • Coffee
  • Tea
  • Water
  • Milk

After appending:

  • Coffee
  • Tea
  • Milk

Water

Example

Create a <p> element and append it to a <div> element:

var para = document.createElement(«P»);                       // Create a <p> nodevar t = document.createTextNode(«This is a paragraph.»);      // Create a text nodepara.appendChild(t);                                          // Append the text to <p>
document.getElementById(«myDIV»).appendChild(para);           // Append <p> to <div> with id=»myDIV»

Example

Create a <p> element with some text and append it to the end of the document
body:

var x = document.createElement(«P»);                        // Create a <p> nodevar t = document.createTextNode(«This is a paragraph.»);    // Create a text nodex.appendChild(t);                                           // Append the text to <p>document.body.appendChild(x);                               // Append <p> to <body>

DocumentFragment

является специальным DOM-узлом, который служит обёрткой для передачи списков узлов.

Мы можем добавить к нему другие узлы, но когда мы вставляем его куда-то, он «исчезает», вместо него вставляется его содержимое.

Например, ниже генерирует фрагмент с элементами , которые позже вставляются в :

Обратите внимание, что на последней строке с мы добавляем , но он «исчезает», поэтому структура будет:

редко используется. Зачем добавлять элементы в специальный вид узла, если вместо этого мы можем вернуть массив узлов? Переписанный пример:

Мы упоминаем в основном потому, что он используется в некоторых других областях, например, для элемента template, который мы рассмотрим гораздо позже.

Drawback of Using InnerHTML to Add a New HTML Node

  • The works by deleting the HTML content inside the element and then adding them back again with the new piece of HTML included in it. In essence, it replaces the HTML content rather than just adding a new one.
  • When we add a new HTML element to the DOM with the property, it will remove all the descendant nodes too and then replace them with the new nodes built by parsing the new HTML content (the HTML string that is assigned to property) and render the entire HTML afresh.
  • It is not much known that while using in a project which undergoes a cybersecurity review, the code can get rejected. It is advisable not to use directly as it may have a potential security risk (for further details, refer to the ).

SelectRootElement

We can also use the to select a node element based on a selector.

Syntax

1
2
3

selectRootElement(selectorOrNodeany,preserveContent?boolean)

 

The first argument is the selector or node. The Renderer2 uses the selector to search for the DOM element and returns it.

The second argument is . If or , the renderer2 will remove all the child nodes. If yes the child nodes are not removed.

Example, consider the following template

1
2
3
4
5
6
7
8
9
10
11
12

<h1>Renderer2 selectRootElement Example</h1>

<div class=»outerDiv»style=»border: 1px solid black; padding :5px;»>

<div class=»div1″style=»border: 1px solid black; margin :5px;»>ThisisDiv1</div>

<div class=»div2″style=»border: 1px solid black; margin :5px;»>ThisisDiv2</div>

<div class=»div3″class=»div3class»style=»border: 1px solid black; margin :5px;»>ThisisDiv3</div>

</div>

 
 

The in the following example returns the element , but it removes all the content it holds. Because the second argument is false. Change to , then the renderer2 will not remove the content.

1
2
3
4
5

exampleDiv1(){

conste=this.renderer.selectRootElement(‘.div1’,false);

}

 

Examples.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

exampleDiv2(){

//Conent is always replaced. becuase preserveContent is false

conste=this.renderer.selectRootElement(‘.div2’,false);

constt=this.renderer.createText(‘Content added to div2’);

this.renderer.appendChild(e,t);

}

exampleDiv3(){

//Conent is always appended. becuase preserveContent is true

conste=this.renderer.selectRootElement(‘.div3’,true);

constt=this.renderer.createText(‘Content added to div3’);

this.renderer.appendChild(e,t);

}

 

Window

Window Object
alert()
atob()
blur()
btoa()
clearInterval()
clearTimeout()
close()
closed
confirm()
console
defaultStatus
document
focus()
frameElement
frames
history
getComputedStyle()
innerHeight
innerWidth
length
localStorage
location
matchMedia()
moveBy()
moveTo()
name
navigator
open()
opener
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
print()
prompt()
resizeBy()
resizeTo()
screen
screenLeft
screenTop
screenX
screenY
scrollBy()
scrollTo()
scrollX
scrollY
sessionStorage
self
setInterval()
setTimeout()
status
stop()
top

Window Console
assert()
clear()
count()
error()
group()
groupCollapsed()
groupEnd()
info()
log()
table()
time()
timeEnd()
trace()
warn()

Window History
back()
forward()
go()
length

Window Location
assign()
hash
host
hostname
href
origin
pathname
port
protocol
reload()
replace()
search

Window Navigator
appCodeName
appName
appVersion
cookieEnabled
geolocation
javaEnabled()
language
onLine
platform
product
taintEnabled()
userAgent

Window Screen
availHeight
availWidth
colorDepth
height
pixelDepth
width

JavaScript

JS Array
concat()
constructor
copyWithin()
entries()
every()
fill()
filter()
find()
findIndex()
forEach()
from()
includes()
indexOf()
isArray()
join()
keys()
length
lastIndexOf()
map()
pop()
prototype
push()
reduce()
reduceRight()
reverse()
shift()
slice()
some()
sort()
splice()
toString()
unshift()
valueOf()

JS Boolean
constructor
prototype
toString()
valueOf()

JS Classes
constructor()
extends
static
super

JS Date
constructor
getDate()
getDay()
getFullYear()
getHours()
getMilliseconds()
getMinutes()
getMonth()
getSeconds()
getTime()
getTimezoneOffset()
getUTCDate()
getUTCDay()
getUTCFullYear()
getUTCHours()
getUTCMilliseconds()
getUTCMinutes()
getUTCMonth()
getUTCSeconds()
now()
parse()
prototype
setDate()
setFullYear()
setHours()
setMilliseconds()
setMinutes()
setMonth()
setSeconds()
setTime()
setUTCDate()
setUTCFullYear()
setUTCHours()
setUTCMilliseconds()
setUTCMinutes()
setUTCMonth()
setUTCSeconds()
toDateString()
toISOString()
toJSON()
toLocaleDateString()
toLocaleTimeString()
toLocaleString()
toString()
toTimeString()
toUTCString()
UTC()
valueOf()

JS Error
name
message

JS Global
decodeURI()
decodeURIComponent()
encodeURI()
encodeURIComponent()
escape()
eval()
Infinity
isFinite()
isNaN()
NaN
Number()
parseFloat()
parseInt()
String()
undefined
unescape()

JS JSON
parse()
stringify()

JS Math
abs()
acos()
acosh()
asin()
asinh()
atan()
atan2()
atanh()
cbrt()
ceil()
clz32()
cos()
cosh()
E
exp()
expm1()
floor()
fround()
LN2
LN10
log()
log10()
log1p()
log2()
LOG2E
LOG10E
max()
min()
PI
pow()
random()
round()
sign()
sin()
sinh()
sqrt()
SQRT1_2
SQRT2
tan()
tanh()
trunc()

JS Number
constructor
isFinite()
isInteger()
isNaN()
isSafeInteger()
MAX_VALUE
MIN_VALUE
NEGATIVE_INFINITY
NaN
POSITIVE_INFINITY
prototype
toExponential()
toFixed()
toLocaleString()
toPrecision()
toString()
valueOf()

JS OperatorsJS RegExp
Modifiers:
g
i
m
Groups:

(x|y)
Metacharacters:
.
\w
\W
\d
\D
\s
\S
\b
\B
\0
\n
\f
\r
\t
\v
\xxx
\xdd
\uxxxx
Quantifiers:
+
*
?
{X}
{X,Y}
{X,}
$
^
?=
?!
Properties:
constructor
global
ignoreCase
lastIndex
multiline
source
Methods:
compile()
exec()
test()
toString()

JS Statements
break
class
const
continue
debugger
do…while
for
for…in
for…of
function
if…else
let
return
switch
throw
try…catch
var
while

JS String
charAt()
charCodeAt()
concat()
constructor
endsWith()
fromCharCode()
includes()
indexOf()
lastIndexOf()
length
localeCompare()
match()
prototype
repeat()
replace()
search()
slice()
split()
startsWith()
substr()
substring()
toLocaleLowerCase()
toLocaleUpperCase()
toLowerCase()
toString()
toUpperCase()
trim()
valueOf()

Removing Nodes from the DOM

Now we know how to create elements, add them to the DOM, and modify existing elements. The final step is to learn to remove existing nodes from the DOM. Child nodes can be removed from a parent with , and a node itself can be removed with .

Method Description
Remove child node
Remove node

Using the to-do example above, we’ll want to delete items after they’ve been completed. If you completed your homework, you can remove the item, which happens to be the last child of the list, with .

todo.html

Another method could be to remove the node itself, using the method directly on the node.

todo.html

Between and , you can remove any node from the DOM. Another method you may see for removing child elements from the DOM is setting the property of a parent element to an empty string (). This is not the preferred method because it is less explicit, but you might see it in existing code.

insertAdjacentHTML

Рассмотренные
выше методы вставки добавляют либо отдельные теги, либо текстовую информацию.
Причем, текст вставляется именно как текст, то есть, теги внутри текста будут
отображены как текст. Например:

document.body.append("Текст с тегом");

Но, что если мы
хотим вставить строку как HTML-строку с обработкой всех тегов, а не
как обычный текст? Как раз для этого используется метод insertAdjacentHTML,
который имеет следующий синтаксис:

elem.insertAdjacentHTML(where, html)

здесь where может принимать
значения:

  • «beforebegin»
    – для вставки html непосредственно перед elem;

  • «afterbegin»
    – для вставки html как первого дочернего элемента в elem;

  • «beforeend»
    – для вставки html как последнего дочернего элемента в elem;

  • «afterend»
    – для вставки html непосредственно после elem.

Для примера
возьмем вот такой список:

<ul>
<li>Меркурий
<li>Венера
<li>Земля
</ul>

И сделаем такие вставки:

let list = document.querySelector("ul.list");
list.insertAdjacentHTML("beforebegin", "Список планет<hr>");
list.insertAdjacentHTML("afterend", "<hr>Конец списка");
list.insertAdjacentHTML("afterbegin", "<li>Солнце");
list.insertAdjacentHTML("beforeend", "<li>Марс");

Смотрите как
разместились эти элементы.

Существует еще
два похожих метода, но более специализированных:

  • insertAdjacentText(where,
    text) – для вставки строки текста text;

  • insertAdjacentElement(where,
    elem) – для вставки элемента
    elem.

Например:

list.insertAdjacentText("beforebegin", "Список планет<hr>");

вставит текст как строку, а

let li = document.createElement("li");
li.innerHTML="Солнце";
list.insertAdjacentElement("afterbegin", li);

добавит
соответствующий элемент.

Однако, на
практике эти два метода почти не применяются. Вместо них удобнее использовать
методы append/prepend/before/after просто потому, что легче писать. Если нам нужно
удалить какой-либо узел из DOM-дерева, то для этого часто используется
метод

node.remove()

Например,
имеется список:

<ul class="list">
<li>Солнце
<li>Меркурий
<li>Венера
<li>Земля
<li>Марс
</ul>

И мы из него
хотим из него удалять последние пункты, пока полностью не очистим. Это можно сделать так:

let idRemove = setInterval(function() {
    let li = document.querySelector("ul.list > li:last-child");
    if(li === null) {
       clearInterval(idRemove);
       alert("Список удален");
    }
    else li.remove();
}, 500);

Connecting to the API

Let’s take a look at the Studio Ghibli API documentation. This API was created to help developers learn how to interact with resources using HTTP requests, which is perfect for us here. Since an API can be accessed by many different methods — JavaScript, PHP, Ruby, Python and so on — the documentation for most APIs doesn’t tend to give specific instructions for how to connect.

We can see from this documentation that it tells us we can make requests with or regular REST calls, but we might not have a clue how to do that yet.

Obtaining the API endpoint

To get started, let’s scroll to the . On the right you’ll see . It will show us the URL of our API endpoint, https://ghibliapi.herokuapp.com/films. Clicking on that link will display an array of objects in JSON.

Retrieving the data with an HTTP request

Before we try to put anything on the front end of the website, let’s open a connection the API. We’ll do so using objects, which is a way to open files and make an HTTP request.

We’ll create a variable and assign a new object to it. Then we’ll open a new connection with the method — in the arguments we’ll specify the type of request as as well as the URL of the API endpoint. The request completes and we can access the data inside the function. When we’re done, we’ll send the request.

scripts.js

Alternatively, you can use the API and /.

Working with the JSON response

Now we’ve received a response from our HTTP request, and we can work with it. However, the response is in JSON, and we need to convert that JSON in to JavaScript objects in order to work with it.

We’re going to use to parse the response, and create a variable that contains all the JSON as an array of JavaScript objects. Using , we’ll console log out the title of each film to ensure it’s working properly.

scripts.js

Using Inspect on index.html and viewing the console, you should see the titles of 20 Ghibli films. Success!

The only thing we’re missing here is some way to deal with errors. What if the wrong URL is used, or the URL broke and nothing was being displayed? When an HTTP request is made, the response returns with HTTP status codes. is the most well-known response, meaning Not Found, and OK is a successful request.

Let’s just wrap our code in an statement, succeeding on any response in the 200-300 range, and log out an error if the request fails. You can mess up the URL to test the error.

scripts.js

Here is the entire code so far.

scripts.js

We’ve successfully used a HTTP request to retrieve (or consume) the API endpoint, which consisted of data in JSON format. However, we’re still stuck in the console — we want to display this data on the front end of the website, which we’ll do by modifying the DOM.

Creating New Nodes

In a static website, elements are added to the page by directly writing HTML in an file. In a dynamic web app, elements and text are often added with JavaScript. The and methods are used to create new nodes in the DOM.

Property/Method Description
Create a new element node
Create a new text node
Get or set the text content of an element node
Get or set the HTML content of an element

To begin, let’s create an file and save it in a new project directory.

index.html

Right click anywhere on the page and select “Inspect” to open up Developer Tools, then navigate to the Console.

We will use on the object to create a new element.

We’ve created a new element, which we can test out in the Console.

The variable outputs an empty element, which is not very useful without any text. In order to add text to the element, we’ll set the property.

A combination of and creates a complete element node.

An alternate method of setting the content of the element is with the property, which allows you to add HTML as well as text to an element.

Note:
While this will work and is a common method of adding content to an element, there is a possible risk associated with using the method, as inline JavaScript can be added to an element. Therefore, it is recommended to use instead, which will strip out HTML tags.

It is also possible to create a text node with the method.

With these methods, we’ve created new elements and text nodes, but they are not visible on the front end of a website until they’ve been inserted into the document.

Подробнее о getUserMedia: запуск/остановка веб-камеры, снимки экрана, фильтры CSS и т. д.

Рассмотрим несколько примеров того, что можно сделать с помощью API getUserMedia: запустить/остановить веб-камеру, сделать снимок экрана с текущего видеопотока с веб-камеры и применить эффекты CSS в режиме реального времени.

Важно! В приведенных ниже примерах видео записывается вместе со звуком, поэтому при включении камеры необходимо отключить воспроизведение звука на вашем устройстве (громкость на мобилке или колонки на ПК)

Иначе микрофон будет принимать звук, к нему будет подмешивается тот же звук, но уже из динамиков, звук быстро усиливается в арифметической прогрессии и происходит перегрузка уровня звука (как на концертах: иногда артисты по неосторожности попадают с микрофоном в зону динамиков, и появляется сильный визг из колонок). Среди звукорежиссеров этот эффект называется акустическая обратная связь (усиление в замкнутой петле больше единицы, так что происходит самовозбуждение)

Среди звукорежиссеров этот эффект называется акустическая обратная связь (усиление в замкнутой петле больше единицы, так что происходит самовозбуждение).

Как остановить/включить веб-камеру

Чтобы остановить веб-камеру и заставить устройство «разблокировать ее», необходимо вызвать метод stop () видеопотока:

Start WebCam
Stop WebCam

Quick overview

API stands for Application Program Interface, which can be defined as a set of methods of communication between various software components. In other words, an API allows software to communicate with another software.

We’ll be focusing specifically on Web APIs, which allow a web server to interact with third-party software. In this case, the web server is using HTTP requests to communicate to a publicly available URL endpoint containing JSON data. If this is confusing now, it will make sense by the end of the article.

You may be familiar with the concept of a CRUD app, which stands for Create, Read, Update, Delete. Any programming language can be used to make a CRUD app with various methods. A web API uses HTTP requests that correspond to the CRUD verbs.

Action HTTP Method Description
Create Creates a new resource
Read Retrieves a resource
Update Updates an existing resource
Delete Deletes a resource

Animation

Usually, the cleanest way to perform animations is to apply CSS classes with a property, or use CSS . But if you need more flexibility (e.g. for a game), this can be done with JavaScript as well.

The naive approach would be to have a function call itself until the desired animation is completed. However, this inefficiently forces rapid document reflows; and this layout thrashing can quickly lead to stuttering, expecially on mobile devices. Intead, we can sync the updates using to schedule all current changes to the next browser repaint frame. It takes a callback as argument which receives the current (high res) timestamp:

This way we can achieve very smooth animations. For a more detailed discussion, please have a look at this article by Mark Brown.

Using insertAdjacentHTML() to Add HTML Node

The and even the functions are capable of adding new elements to the given HTML node. Both these methods insert the element after the last child. It may not be useful for all scenarios. Especially if we wish to add the HTML node at a specified position in the HTML structure. For such cases function can be used. It takes a couple of parameters, the position and the text in that position.

  • : supports four values in the position parameter.

    • : To insert the HTML node before the start of the element.
    • : As the name suggests, this option inserts the element just after the opening tag of the selected node and places it before the first child.
    • : This one is similar to the . As the name suggests, the position places the element just after the last child.
    • : Refers to the position after the target HTML node tag closes.
  • : We can insert the HTML in the string format as a second parameter. For example: .

At a glance, the representation is as follows.

Let us look at the same example as we discussed for with the function of JavaScript.

In this code, we have used the option in the parameter to append the dynamically created input element at the end of the div. You can try playing around with the other attributes like the , , and parameters.

Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Гость форума
От: admin

Эта тема закрыта для публикации ответов.