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

Не могу понять что это?
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);
код не понятен такое впечатления автор пишет это сам для себя а не для людей.

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:

    • what you are trying to do
    • what you have tried
    • any syntax errors ect
  • 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 переводчик из-за российского брандмауэра, скажите об этом

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

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>

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

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

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.

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)

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.

<!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)

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

:slight_smile:

1 Like