# Question from kirupa's book? (Вопрос из книги кирупа)

**URL:** <https://forum.kirupa.com/t/question-from-kirupas-book/651453>\
**Category:** Uncategorized\
**Created:** [April 8, 2022, 6:13pm UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453 "2022-04-08T18:13:56Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![forumf](https://avatars.discourse-cdn.com/v4/letter/f/a6a055/32.png) [@forumf](https://forum.kirupa.com/u/forumf)\
**Post date:** [April 8, 2022, 6:13pm UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/1 "2022-04-08T18:13:56Z")

</div>

Не могу понять что это?  
let newElement = document.createElement(“p”);  
let bodyElement = document.querySelector(“body”);  
let h1Element = document.querySelector(“h1”);  
newElement.textContent = “I exist entirely in your imagination.”;  
bodyElement.insertBefore(newElement, h1Element.nextSibling);  
код не понятен такое впечатления автор пишет это сам для себя а не для людей.

---

<div class="post-metadata">

**Author:** ![steve.mills](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/steve.mills/32/14961_2.png) [@steve.mills](https://forum.kirupa.com/u/steve.mills)\
**Post date:** [April 10, 2022, 4:33am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/2 "2022-04-10T04:33:27Z")

</div>

Look mate a few points:

- Most of the people that help you out on this forum have full time jobs, families ect

- You cant expect that you have an entitlement to an urgent response when you are getting free community advice… (this is what “open source” has done to expectations)

- Any other forum that offers help would expect that when you post a question you provide some code to show:

- We kind of expect the same… but unlike other forums we don’t tell you to go away…

- Calling the forum “fake” and getting snarky doesn’t really make anybody want to respond

- You were asked to post in English (use Google translate) so other people can see the thread without everybody wanting to view it having to do it themselves.

- If you cant use Google translate because of a Russian firewall please say so

Смотри, приятель, несколько моментов:

```
Большинство людей, которые помогают вам на этом форуме, имеют работу на полную ставку, семьи и т. д.

Вы не можете ожидать, что у вас есть право на срочный ответ, когда вы получаете бесплатный совет сообщества… (вот что «открытый исходный код» сделал с ожиданиями)

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

Мы ожидаем того же… но, в отличие от других форумов, мы не просим вас уйти…

Называть форум «фальшивкой» и язвить на самом деле не заставляет никого хотеть отвечать

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

Если вы не можете использовать Google переводчик из-за российского брандмауэра, скажите об этом
```

---

<div class="post-metadata">

**Author:** ![forumf](https://avatars.discourse-cdn.com/v4/letter/f/a6a055/32.png) [@forumf](https://forum.kirupa.com/u/forumf)\
**Post date:** [April 10, 2022, 7:00am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/3 "2022-04-10T07:00:54Z")

</div>

Это все понятно,но от этого новички умнее не стают,и хочется разбирать вопрос по коду,а не кто когда отвечает и на данный момент ответа вы не дали,1 что бы что то сделать надо понимать что и как делать,из вашего материала понять не возможно,2 а что можно пробовать если ученики не чего не поняли? 3 вы когда выпускаете книгу в свет о чем думаете?на пример из 20 учеников не один не понимает ваш материал,это говорит о том что она глупая так получается?

---

<div class="post-metadata">

**Author:** ![steve.mills](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/steve.mills/32/14961_2.png) [@steve.mills](https://forum.kirupa.com/u/steve.mills)\
**Post date:** [April 10, 2022, 7:19am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/4 "2022-04-10T07:19:41Z")

</div>

English:  
I can’t figure out what it is?  
let newElement = document.createElement(“p”);  
let bodyElement = document.querySelector(“body”);  
let h1Element = document.querySelector(“h1”);  
newElement.textContent = “I exist entirely in your imagination.”;  
bodyElement.insertBefore(newElement, h1Element.nextSibling);  
the code is not clear such an impression the author writes it for himself and not for people.

Response:  
It looks pretty clear to me but I’ll try to simplify further

`let paragraph_Element = document.createElement("p");`

- create a paragraph(`p`) element and store in memory as` let paragraph_Element`

`let body_Element = document.querySelector("body");`

- find the` <body>` element on the web page and store a pointer in memory as` let body_Element`

`let heading1_Element = document.querySelector("h1");`

- find the first `<h1`\> on the web page and store a pointer in memory as` let heading1_Element`

`paragraph_Element.textContent = "I exist entirely in your imagination.";`

- make the `textContent` property of `paragraph_Element` = “I exist entirely in your imagination.”

`body_Element.insertBefore(paragraph_Element, heading_1Element.nextSibling);`

- reference the `<body>`, call the `insertBefore()` method and insert a new child element `<p>"I exist entirely in your imagination."</p>` before the first `<h1>` child element.

Russian:  
Мне это кажется довольно ясным, но я постараюсь упростить дальше

`let para_Element = document.createElement("p");`

- создайте элемент абзаца (`p`) и сохраните в памяти как `let section_Element`

`let body_Element = document.querySelector("тело");`

- найти элемент `<body>` на веб-странице и сохранить указатель в памяти как `let body_Element`

`let heading1_Element = document.querySelector("h1");`

- найти первый `<h1`\> на веб-странице и сохранить указатель в памяти как `let heading1_Element`

`paragraph_Element.textContent = "Я существую исключительно в вашем воображении.";`

- сделать свойство `textContent` для `paragraph_Element` = “Я существую полностью в твоем воображении”.

`body_Element.insertBefore(paragraph_Element, heading_1Element.nextSibling);`

- сослаться на `<body>`, вызвать метод `insertBefore()` и вставить новый дочерний элемент `<p>"Я существую полностью в вашем воображении."</p>` перед первым дочерним элементом `<h1>`

---

<div class="post-metadata">

**Author:** ![forumf](https://avatars.discourse-cdn.com/v4/letter/f/a6a055/32.png) [@forumf](https://forum.kirupa.com/u/forumf)\
**Post date:** [April 10, 2022, 9:36am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/5 "2022-04-10T09:36:08Z")

</div>

Все ровно не чего понять не возможно.  
let para\_Element = document.createElement(“p”);тут я понимаю так создали в переменной para\_Element тег

,потом уже не чего не ясно,откуда взялось это let section\_Element?и все что ниже понимать сложно,что бы добавить тег в документ в javascript надо писать такой сложный код,проще ведь написать сразу в html тег это ведь в 100 раз проще)))

---

<div class="post-metadata">

**Author:** ![steve.mills](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/steve.mills/32/14961_2.png) [@steve.mills](https://forum.kirupa.com/u/steve.mills)\
**Post date:** [April 10, 2022, 11:20am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/6 "2022-04-10T11:20:17Z")

</div>

> It’s impossible to understand everything.  
> let para\_Element = document.createElement(“p”); here I understand that we created a tag in the para\_Element variable
> 
> , then it’s not clear where this let section\_Element came from? and everything below is difficult to understand, in order to add a tag to a document in javascript, you need to write such complex code, it’s easier to write a tag in html right away, it’s 100 times easier)) )

You need to think of it as 2 separate concepts.

- Live DOM- on the page, displayed, interactive, click-able that you have to query with `document.querySelector()` or `document.getElementById()`
- “Virtual DOM”- any DOM nodes that you have created and saved in memory as JS variables (maybe as a template) e.g` let tempate = "<template><h1>SHOUT!</h1></template>"`

If you understand HTML better you could also do:  
`document.querySelector("h1").insertAdjacentHTML(`“beforebegin”`, "<p> `“I exist entirely in your imagination.”`</p>")`

If you have no interest in Javascript at the very least you should learn how to run a function `onclick()` that will change `CSS classes` so that you can animate your pages.

HTML and CSS can pretty much do the rest excluding changing HTML without a page change.

---

<div class="post-metadata">

**Author:** ![forumf](https://avatars.discourse-cdn.com/v4/letter/f/a6a055/32.png) [@forumf](https://forum.kirupa.com/u/forumf)\
**Post date:** [April 10, 2022, 6:43pm UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/7 "2022-04-10T18:43:17Z")

</div>

Yes, I have not had an understanding of the Javascript language for a year now, the result is zero, I also don’t understand why it is needed, like in styles you can do everything necessary for layout, it’s very unclear why such a complex language is needed)

---

<div class="post-metadata">

**Author:** ![steve.mills](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/steve.mills/32/14961_2.png) [@steve.mills](https://forum.kirupa.com/u/steve.mills)\
**Post date:** [April 11, 2022, 12:35am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/8 "2022-04-11T00:35:58Z")

</div>

This is the minimum Javascript you should know to be able to make interactive pages using CSS classes and not resorting to check box hacks.

```auto
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
<style>
    *{ margin: 50px }
    .red{ background-color: red; }
    .green{
         background-color: green;
         transform: rotateZ(45deg);
    }
    #box{
        height: 200px;
        width: 200px;
    }
</style>
</head>
<body>
    <div id = 'box' class = 'red'></div>
    <br>
    <button onclick="document.getElementById('box').classList.toggle('green')">Change Color and Rotate</button>
</body>\
</html>

```

The Javascript is in the button `onclick""` attribute which will run a `function or expression` on a click event.

This saves you from adding `<script>` and `defer` or waiting for `DOMContentLoaded` and adding `eventListener()` and `functions()`

The expression will find the element with `id ="box"` and add or remove (toggle) the CSS class `'green'`

For this to work the `toggled class` must either be a `higher CSS specificity` or be placed below the other class (green below red) in the cascade.

The `"green" class` basically **overrides** the` "red" class` every time it is **added** and the `"red" class` is **applied** when the “green” class is **removed** (by toggling)

---

<div class="post-metadata">

**Author:** ![kirupa](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/kirupa/32/11616_2.png) [@kirupa](https://forum.kirupa.com/u/kirupa)\
**Post date:** [April 11, 2022, 2:46am UTC](https://forum.kirupa.com/t/question-from-kirupas-book/651453/9 "2022-04-11T02:46:26Z")

</div>

To add to Steve’s excellent answer, this article goes into detail on how you can use JavaScript to modify CSS:

> **[Setting CSS Styles Using JavaScript](https://www.kirupa.com/html5/setting_css_styles_using_javascript.htm)**
>
> Learn about the two awesome ways you have available for styling your content using JavaScript.

🙂
