Skip to content

Commit 01cedb3

Browse files
committed
[TM-17.13/st-compl] training-module
Solving 9 tasks. Working with "textContent, storage, inline-styles" etc. Worth noting: - all this tasks (note the solutions). FS-dev: B-3 / JS basic
1 parent a464941 commit 01cedb3

File tree

3 files changed

+278
-0
lines changed

3 files changed

+278
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
4+
<head>
5+
<meta charset="UTF-8">
6+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
7+
<title>Training</title>
8+
<link rel="preconnect" href="https://fonts.googleapis.com">
9+
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
10+
<link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100..900;1,100..900&display=swap"
11+
rel="stylesheet">
12+
<link rel="stylesheet" href="./style.css">
13+
<script src="./training.js" defer></script>
14+
</head>
15+
16+
<body class="body">
17+
<h1 class="welcome-message">Добро пожаловать на наш сайт!</h1>
18+
<span class="status" id="status">Не готово!</span>
19+
<div class="content"></div>
20+
<input id="username" type="text" autocomplete="on">
21+
<div class="temporary-banner">Так держать!</div>
22+
<div class="profile-card active" id="user-profile" data-user="123">Информация о пользователе</div>
23+
<button class="styled-button"
24+
style="width: 100%; max-width: 130px; min-height: 30px; font-weight: 600;">Применить</button>
25+
<button class="plain-button">Отменить</button>
26+
<nav class="menu-item active">
27+
<ul class="menu-list">
28+
<li class="menu-list">О нас</li>
29+
<li class="menu-list">Проекты</li>
30+
<li class="menu-list">Контакты</li>
31+
</ul>
32+
</nav>
33+
</body>
34+
35+
</html>
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
.body {
2+
font-family: "Roboto", sans-serif;
3+
}
4+
5+
#username {
6+
margin-bottom: 10px;
7+
}
8+
9+
.temporary-banner {
10+
margin-bottom: 10px;
11+
}
12+
13+
.profile-card {
14+
margin-bottom: 10px;
15+
}
16+
17+
.styled-button,
18+
.plain-button {
19+
border: none;
20+
padding: 10px 15px;
21+
background: lightblue;
22+
letter-spacing: 1px;
23+
cursor: pointer;
24+
transition: background 0.2s ease-in-out;
25+
will-change: background;
26+
}
27+
28+
.styled-button:hover,
29+
.plain-button:hover {
30+
background: lightcyan;
31+
}
Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,212 @@
1+
'use strict';
2+
3+
// Задание 1:
4+
// Напишите логику, которая находит элемент на веб-странице по CSS-селектору и выводит его текстовое содержимое в консоль.
5+
6+
function findAndDisplayElement(selector) {
7+
const element = document.querySelector(selector);
8+
9+
if (!element) {
10+
console.log(`Элемент не найден по селектору: ${selector}`);
11+
return;
12+
}
13+
14+
const message = element.textContent;
15+
16+
console.log(message); // "Добро пожаловать на наш сайт!"
17+
}
18+
19+
findAndDisplayElement('.welcome-message');
20+
21+
// Задание 2:
22+
// Напишите логику, которая изменяет текстовое содержимое HTML-элемента на новое значение.
23+
24+
function changeContent(selector, newText) {
25+
if (!newText || typeof newText !== 'string') {
26+
return false;
27+
}
28+
29+
newText = newText.trim();
30+
const element = document.querySelector(selector);
31+
32+
if (element) {
33+
element.textContent = newText;
34+
return true;
35+
}
36+
37+
return false;
38+
}
39+
40+
console.log(changeContent('#status', 'Готово!')); // true
41+
42+
// Задание 3:
43+
// Напишите логику, которая создает новый HTML-элемент с заданным тегом и добавляет его в указанный контейнер на странице.
44+
45+
function createNewElement(tag, selector) {
46+
if (!tag || typeof tag !== 'string') {
47+
return '';
48+
}
49+
50+
tag = tag.trim();
51+
const container = document.querySelector(selector);
52+
53+
if (!container) {
54+
console.log(`Контейнер по селектору: ${selector}, не найден!`);
55+
return;
56+
}
57+
58+
const newElement = document.createElement(tag);
59+
newElement.textContent = 'Я новый элемент!';
60+
61+
container.append(newElement);
62+
63+
console.log(
64+
`Новый элемент <${tag}> добавлен внутрь элемента, соответствующего селектору '${selector}'`
65+
); // "Новый элемент <p> добавлен внутрь элемента, соответствующего селектору '.content'"
66+
}
67+
68+
createNewElement('p', '.content');
69+
70+
// !! Задание 4:
71+
// Напишите логику, которая получает значение из input поля и сохраняет его в Local Storage браузера под указанным ключом.
72+
73+
function addValueToStorage(selector, key) {
74+
if (!key || typeof key !== 'string') {
75+
return '';
76+
}
77+
78+
const element = document.querySelector(selector);
79+
80+
if (!element) {
81+
console.log(`Элемент не найден по селектору: ${selector}`);
82+
return;
83+
}
84+
85+
element.addEventListener('input', () => {
86+
let value = element.value;
87+
localStorage.setItem(key, JSON.stringify(value));
88+
}); // !! без прослушки/без события "input" обрабатывать/получать "текущие" (вот/только введённые) данные не получится
89+
90+
console.log(
91+
`Значение из поля с селектором ${selector} сохранено в localStorage под ключом ${key}`
92+
); // "Значение из поля с селектором #username сохранено в localStorage под ключом user_name"
93+
}
94+
95+
addValueToStorage('#username', 'user_name');
96+
97+
// !! Задание 5:
98+
// Напишите логику, которая удаляет HTML-элемент со страницы по указанному CSS-селектору.
99+
100+
function deleteElement(selector) {
101+
const element = document.querySelector(selector);
102+
103+
if (!element) {
104+
console.log(`Элемент не найден по селектору: ${selector}`);
105+
return;
106+
}
107+
108+
element.remove();
109+
110+
console.log(`Элемент с селектором ${selector}, удалён успешно!`); // "Элемент с селектором .temporary-banner, удалён успешно!"
111+
}
112+
113+
deleteElement('.temporary-banner');
114+
115+
// !! Задание 6:
116+
// Напишите логику, которая получает все атрибуты HTML-элемента и выводит их в виде объекта в консоль.
117+
118+
function getAttributes(selector) {
119+
const element = document.querySelector(selector);
120+
121+
if (!element) {
122+
console.log(`Элемент не найден по селектору: ${selector}`);
123+
return;
124+
}
125+
126+
const attributesObj = {};
127+
128+
for (const attr of element.attributes) {
129+
attributesObj[attr.name] = attr.value;
130+
}
131+
132+
console.log(attributesObj); // {class: 'profile-card active', id: 'user-profile', data-user: '123'}
133+
}
134+
135+
getAttributes('#user-profile');
136+
137+
// !! Задание 7:
138+
// Напишите логику, которая копирует все CSS-стили одного элемента и применяет их к другому элементу на странице.
139+
140+
function changeInlineStyle(sourceSelector, recipientSelector) {
141+
const sourceElement = document.querySelector(sourceSelector);
142+
const recipientElement = document.querySelector(recipientSelector);
143+
144+
if (!sourceElement) {
145+
console.log(`Элемент-источник не найден по селектору: ${sourceSelector}`);
146+
return;
147+
}
148+
if (!recipientElement) {
149+
console.log(
150+
`Элемент-получатель не найден по селектору: ${recipientSelector}`
151+
);
152+
return;
153+
}
154+
155+
recipientElement.style.cssText = sourceElement.style.cssText;
156+
157+
console.log(
158+
`Стили с элемента '${sourceSelector}' были скопированы на элемент '${recipientSelector}'`
159+
); // "Стили с элемента '.styled-button' были скопированы на элемент '.plain-button'"
160+
}
161+
162+
changeInlineStyle('.styled-button', '.plain-button');
163+
164+
// Задание 8:
165+
// Напишите логику, которая находит все элементы на странице с определенным тегом и подсчитывает их количество.
166+
167+
function countDOMElements(tag) {
168+
if (!tag || typeof tag !== 'string' || tag.trim() === '') {
169+
return '';
170+
}
171+
172+
tag = tag.trim().toLowerCase();
173+
const elements = document.querySelectorAll(tag);
174+
175+
if (!elements || elements.length === 0) {
176+
console.log(`Элементы не найдены по тегу: ${tag}`);
177+
return;
178+
}
179+
180+
const count = elements.length;
181+
182+
console.log(`Элементов '${tag}' вот такое количество: ${count} на странице!`); // "Элементов 'div' вот такое количество: 2 на странице!"
183+
}
184+
185+
countDOMElements('div');
186+
187+
// Задание 9:
188+
// Напишите логику, которая находит элемент на странице и проверяет, содержит ли он определенный CSS-класс.
189+
190+
function getAllClasses(selector, className) {
191+
if (!className || typeof className !== 'string' || className.trim() === '') {
192+
console.log(`Передано не корректное имя класса: ${className}`);
193+
return false;
194+
}
195+
196+
className = className.trim();
197+
const element = document.querySelector(selector);
198+
199+
if (!element) {
200+
console.log(`Элемент не найден по селектору: ${selector}`);
201+
return false;
202+
}
203+
204+
const classList = Array.from(element.classList);
205+
const result = classList.includes(className);
206+
207+
console.log(result); // true
208+
209+
return result;
210+
}
211+
212+
getAllClasses('.menu-item', 'active');

0 commit comments

Comments
 (0)